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




  1. Right click on the project in solution explorer and click on ‘Properties’.
  2. Picture showing the context menu for opening the properties window in C# project
    Click to Enlarge

  3. In the ‘Application’ tab, click on ‘Assembly Information’ button.
  4. Picture showing the properties window of the C# project
    Click to Enlarge

  5. A pop-up window will appear. Click on the checkbox ‘Make assembly COM-visible’ and click on ‘Ok’.
  6. Picture showing the popup window to check the option Make Assembly Com Visible
    Click to Enlarge

  7. Go to the ‘Build’ tab and click on the checkbox ‘Register for COM interop’.
  8. Picture showing the Build tab to enable Register for COM interop option
    Click to Enlarge

  9. Save the project and compile again.

Register The DLL Using Regasm




  1. Open command prompt in administrator mode.
  2. In the command prompt, enter the following command
  3. C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe C:\temp\ComVisibleLibrary\SampleComVisibleLibrary\SampleComVisibleLibrary\bin\Debug\SampleComVisibleLibrary.dll /codebase




  4. Press ‘Enter’
  5. Picture showing the command prompt to register the DLL using RegAsm utility
    Click to Enlarge

Add Reference Of C# Library In VBA




  1. In the code editor, click on Tools - ‘References’
  2. Picture showing the References option in the code editor for adding the reference of C# library
    Click to Enlarge

  3. A pop-up window will appear.
  4. Picture showing the pop up window for adding the reference of the C# library
    Click to Enlarge

  5. 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




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