Joachim Brolin
Joachim Brolin

Reputation: 111

How to instantiate a vba class and call a method from vb.net?

As I guess many are, I'm sitting with an ms access application with a mixture of tables, VBA Modules and VBA Classes. I intend to migrate that application to VB.NET.

However it will take some time and I would like to make use of automation to slowly move the code to VB.NET

Now I can call regular SUB and Functions from my VB.NET application but wonder if there is a way to invoke the methods of user defined objects.

Rough example what I want to do

VBA

'Class1
Public Sub Test()
  Print "Hello world"
End Sub

'Module1
Public oClass1 as Class1
Public Sub Init()
  Set oClass1 = New Class1
End Sub

VB.Net

' Left out the opening of the access db
oAccess.Run("Init")
oAccess.Run("oClass1.Test())

Is it even possible?

Upvotes: 3

Views: 1050

Answers (1)

HansUp
HansUp

Reputation: 97121

The Application.Run method requires a string containing "The name of the Function or Sub procedure to be run" as its first argument. But "oClass1.Test" is neither.

You could work around that issue by creating another VBA procedure which wraps your oClass1.Test method, and run the wrapper procedure ...

oAccess.Run("Wrap_oClass1_Test") ' no parentheses after procedure name

Public Sub Wrap_oClass1_Test()
    oClass1.Test
End Sub

I confirmed that approach worked with the rest of your sample code when called from VBScript so I believe it should also work from VB.Net.

Tim's CallByName suggestion also looks promising, but I didn't test that one.

Upvotes: 3

Related Questions