Articles → VBA FOR EXCEL → Call C# Code From VBA
Call C# Code From VBA
Create A C# Library
using System;
using System.IO;
namespace SampleComVisibleLibrary {
public class SampleComVisibleClass {
public void WriteTimeStampInLogFile() {
string str = System.Guid.NewGuid().ToString();
string path = string.Format(@"c:\temp\Log_{0}", str);
File.WriteAllText(path, DateTime.Now.ToLongDateString());
}
}
}
Make C# Class Library Com Visible
- Right click on the project in solution explorer and click on ‘Properties’.
Click to Enlarge
- In the ‘Application’ tab, click on ‘Assembly Information’ button.
Click to Enlarge
- A pop-up window will appear. Click on the checkbox ‘Make assembly COM-visible’ and click on ‘Ok’.
Click to Enlarge
- Go to the ‘Build’ tab and click on the checkbox ‘Register for COM interop’.
Click to Enlarge
- Save the project and compile again.
Register The DLL Using Regasm
- Open command prompt in administrator mode.
- In the command prompt, enter the following command
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe C:\temp\ComVisibleLibrary\SampleComVisibleLibrary\SampleComVisibleLibrary\bin\Debug\SampleComVisibleLibrary.dll /codebase
- Press ‘Enter’
Click to Enlarge
Add Reference Of C# Library In VBA
- In the code editor, click on Tools - ‘References’
Click to Enlarge
- A pop-up window will appear.
Click to Enlarge
- Select the C# library i.e. ‘SampleComVisibleLibrary’ and click on ‘Ok’.
Use C# Library
Sub SampleComVisibleAssembly()
Dim obj As New SampleComVisibleClass
obj.WriteTimeStampInLogFile
End Sub
Output
Click to Enlarge