Home » excel » Use a function of an ATL library in a vbasic macro in Excel

Use a function of an ATL library in a vbasic macro in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I succeed to create a ATL library in c++ which does some operation and gives back solutions. So I have all the functions in excel by using automation. Now I would like to create a macro which could do all the functions in the right order and after that maybe associating a button to it.
So I’ve written this macro:

Sub Macro_test()

 Dim r As Integer

 r = setValInput(Range("F21"), Range("G21"))
 r = initializeCalculation()
 Range("C24") = r
 r = getResult("C21")


End Sub

If i build this Excel says the function setValInput isn’t definite. The class of ATL is named OPclass, maybe have I to do something with this?

How to&Answers:

You create object using CreateObject method. The argument is the ProgID value you provided to C++ ATL wizard when you created the COM class, or/and you can look it up in the project .RGS files.

Code snippet:

   Set MyServer = CreateObject("ProgettoOPserver")
   MyServer.setValInput(Range("F21"), Range("G21"))

Methods and properties on the ATL class exposed through implemented interface will be automatically available to your VBA script code.

Another option is to first add a reference to the external COM server (ATL based library) and instead of CreateObject you would be able to use New operator. See more on this: How to add a reference programmatically. The advantage is that you will be able to see the available methods in Object Browser.

Answer:

A method that’s a member of a class object needs to be called from an instance of the class object. As you have already created OPClass module which presumably contains the method setValInput, try something like:

Dim op as New OPClass
Debug.Print op.setValInput(Range("F21"),Range("G21"))

This assumes you have elsewhere created the object, per Roman’s answer.