I have an Excel add-in with a class module. I want to instantiate the class module in C# and call a method on it. How do I do that?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you really need access to an instance of the class, you could do the following:
Generate a type library for a COM interface that you want to expose from your VBA class (e.g. IMyComInterface)
Add a reference to this type library in your VBA project
Implement the interface in your VBA class module – e.g. MyVbaClass (use the Implements keyword):
Reference the same type library in your C# project
Create a ComVisible C# class with a method that accepts a reference to the VBA interface instance. Something like:
Write a “factory” method in a VBA standard module, that takes an object as a ByRef parameter. This object should assume the object passed as an argument has a property “MyComInterface” and should set this property to a new instance of the VBA class MyClass.
Call the factory method from your C# code. Assuming you have opened the workbook and have a refence “workbook” in your VBA code, the code will look something like:
As you can see, it’s rather complex. Without more detail of the problem you’re trying to solve it’s difficult to say whether this complexity is justified, or whether there’s a simpler solution.
If the above isn’t clear, let me know and I’ll try to clarify.
Basically you can’t return a value from a VBA macro called from your C# code using Application.Run, so you have to resort to passing an object by value that has a method or property that can be called from VBA to set the instance.