Runtime error referencing VBA assembly from C#

2019-02-25 15:42发布

问题:

I have a C# .NET 3.5 project that unfortunately relies on a couple of VB6 ActiveX controls.

Up until now I have been able to happily access the data containers and methods defined in the ActiveX controls by simply adding a reference to the controls in my project and referencing them as normal.

However I hit a snag today when I had to call a method that returns a VBA.Collection.

My code will compile with no problem, but at runtime I get the following error:

Could not load file or assembly 'Interop.VBA, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I have references to Interop.VBA (version 6.0.0.0) and Interop.VBRUN (version 6.0.0.0) in my project, any thoughts?

I can't give specific code, it is covered under an NDA.

However, here is sample code from object browser with names changed to protect the not so innocent ;)

I can reference the following properties and methods from my code:

ReturnConstants GoodMethod(); 
string prop1 
ReturnConstants prop2 

If I try can call this method I get the error message above at runtime:

Collection BadMethod();

So it the call to the method that returns a VBA.Collection that causes the issue. These are 3rd party controls that I have no control over and they will not be rewritten in .net

edit: Out of interest I went and tried a quick dummy project in VS2010 and worked perfectly as expected, so it appears that this may be an issue with VS2012. I've seen some posts that hint at 2012 not creating interops for VBA correctly, so I'll go see what I can find there ...

回答1:

Thanks to @Jeremy Thompson for putting me on the right track, running process monitor showed me that my application was unable to locate the interop.VBA.dll file, once that was fixed everything works as expected. No idea why this works out of the box on 2010 and not 2012, but happy to have a solution