Registered COM DLL works in VBA but not in VBScrip

2019-08-08 14:43发布

问题:

I have created a basic COM DLL with ATL on VS2012. It's called testCOM.dll and it only has one class called CSimpleObj. CSimpleObj has just one method called addValues which adds two values.

I've registered the DLL with Windows 7 64-bit. In VBA, I manually add a reference to the DLL and the below code works properly

Dim Obj As New testCOMLib.SimpleObj
MsgBox Obj.addValues(1,2)

And it give a message with number 3.

Now If I run the vbs which includes:

Dim Obj
Set Obj = CreateObject("testCOMLib.SimpleObj")

It constantly gives an error and is not able to create the object. But if I use the "Excel.Application" ProgID (as an example) for the CreateObject method, it works fine.

I think there is an issue with registering the DLL. I've checked the registry, and the keys for the COM and the type library is already there.

What should I do?

回答1:

There are three basic requirements to get your COM server to be usable from VBScript:

  • You need to implement IDispatch so late binding is supported. Not usually a problem with ATL, it implements it by default when you use the wizards.

  • Your registry script (.rgs) must write the ProgId to the registry. Notable is that you didn't report finding it (look for HKCR\testCOMLib.SimpleObj with Regedit.exe to verify). Its CLSID subkey must match the CLSID in the registry so COM can find your DLL. The ATL Simple Object wizard has a trap, it fills in all the fields when you type the short name. Except for the ProgID field. So very easy to forget.

  • On the 64-bit version of Windows, you'll execute the 64-bit version of cscript.exe by default. It will not be able to find your 32-bit COM server. You'll need to either build the x64 version of your server or you'll need to use the 32-bit version of cscript.exe, located in c:\windows\syswow64. Not usually a problem with VBA since it tends to be used from a 32-bit version of Office.

The SysInternals' Process Monitor utility is very useful to diagnose these kind of problems. You'll see cscript.exe searching the registry for the keys that your server registered. And probably not finding them, you were however not explicit enough about actual error message you got.