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






Picture showing the context menu for opening the properties window in C# project

Click to Enlarge



Picture showing the properties window of the C# project

Click to Enlarge



Picture showing the popup window to check the option Make Assembly Com Visible

Click to Enlarge



Picture showing the Build tab to enable Register for COM interop option

Click to Enlarge




Register the DLL using RegAsm








C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe C:\temp\ComVisibleLibrary\SampleComVisibleLibrary\SampleComVisibleLibrary\bin\Debug\SampleComVisibleLibrary.dll /codebase






Picture showing the command prompt to register the DLL using RegAsm utility

Click to Enlarge


Add reference of C# library in VBA






Picture showing the References option in the code editor for adding the reference of C# library

Click to Enlarge



Picture showing the pop up window for adding the reference of the C# library

Click to Enlarge




Use C# library




Sub SampleComVisibleAssembly()
	
	Dim obj As New SampleComVisibleClass
	obj.WriteTimeStampInLogFile
End Sub



Output




Picture showing the text file created when C# code is invoked using VBA

Click to Enlarge

Posted By  -  Karan Gupta
 
Posted On  -  Monday, October 22, 2018

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250