VS.Net makes COM easy

From Tutorials

Jump to: navigation, search

Versions used: MS Office 2007, VS 2008.

I found myself looking at a VBA for Access screen the other day and not really wanting to code in Visual Basic. If only I could code it all in VS.NET C# and then just compile that into a DLL and reference the DLL inside of Access.

Not having dealt with COM for quite a while, I was surprised at how easy VS.Net makes it now.

These few steps are all that is needed to create a DLL that you can reference in Access.

  • Create your class and method
  • In project settings, in the build section check “Register for COM Interop”
  • In project settings, Application section, “Assembly Info” button, check “Make assembly COM-Visible”
  • Compile
  • In access Tools->References browse to the bin directory for your new project, and select the .tlb that it created during the compile.
  • Write code in VBA

Q: Don’t I need to decorate my class with a GUID attribute ?

A: Apparently not, if you check the registry you’ll see that a GUID actually was generated for your class (Just search for your namespace and it should find yours).

Q: What about an interface to expose the methods in my class ?

A: To get running code you don't need that either. However if you want intellisense in VBA for your methods then it’s a good idea. So note that when you write your VBA code to dim your variables as the interface, and set them as the object you are creating.


Private Sub cmdTest_Click()
 
  Dim result as Integer
  Dim ER as DllReferenceTest.IExampleReference
  Set ER = New DllReferenceTest.ExampleReference
 
  result = ER.GetNumber(7)
  MsgBox (result)
 
End Sub


Of course I haven’t tried to make an installer to publish this dll to another computer and see if it’s still as easy, that is for another day.

Cheers

Personal tools