Home » excel » Passing custom objects from VBA to VBScript

Passing custom objects from VBA to VBScript

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a function in an Excel file that returns a custom class, when i try to call this function from VBScript i get an “Unknown runtime error”

Sample VBA Code:

Function myVBAFunc() As Variant
   Set myClass1 = New Class1
   myClass1.Name = "Test"
   Set myVBAFunc= myClass1
End Function

Calling VBScript code:

Set Excel = CreateObject("Excel.Application") 
Set Workbook = Excel.Workbooks.open("C:\myFile.xls")
Set myRes = Excel.Run("myVBAFunc")
Excel.Quit

I am getting an error when i try to set myRes, I assume this is caused by VBScript not recognizing the object’s type. Is there any way to work around this?

Thanks,
Achraf

How to&Answers:

You need to change the instancing property of the class module (in its property window) from Private to PublicNotCreatable.

(You can also strictly type the function)

Function myVBAFunc() As Class1
   Set myVBAFunc= New Class1
   myVBAFunc.Name = "Test"
End Function