"Invalid use of new keyword" in VBA using old COM object written in C ++

I've tried web and stackoverflow for this answer but can't find anything. I wrote a com object in C ++ (for the first time) that works when used in vbscript and across cocreateinstance

in an executable. So I decided to see if this would work in Excel VBA.

So, I went into Links and found my object there. Marked the box and started coding. Below is the VBA code.

Function doCos(x As Double) As Double
  Dim t As SimpleLib.IMath
  Set t = New SimpleLib.IMath ' <- "Invalid use of New keyword" error here
  doCos = t.Cos(x)
End Function

      

Intellisense recognizes my object in the statement Dim

, but doesn't show up when I use the statement Set

. Obviously I'm using a registered type library, otherwise intellisense won't work at all. Again, com object can be used in vbscript or executable, but for some reason cannot be used, at least with a new keyword in VBA.

Does anyone have any idea what might be wrong or what might be added to the com object? Thank.

+3


source to share


1 answer


One approach is to define a class in IDL that includes the required interface (IMath in my case). NOTE. The interface [default]

is hidden by default. So I just defined it interface IUnknown

as the default. When compiled with MIDL, a type library is generated and must be registered with regtlibv12.exe.

Then I included an additional IF statement in DllGetClassObject

, for example if (rclsid == CLSID_Math)

, where it CLSID_Math

matches the CLSID defined in the file automatically generated from MIDL. All I did was copy and paste the body of the IF statement from if ( rclsid == IID_IMath )

, update the DLLRegisterServer and DLLUnRegisterServer functions, recompile the project and regsvr32.exe.

So now the following works.



Function docos(x As Double) As Double
  Dim a As SimpleLib.IMath
  Set a = New SimpleLib.Math
  docos = a.Cos(x)
End Function

      

Thanks to Hans for the class tip. I learned something new and useful.

+1


source







All Articles