How do I declare a function in VBA which accepts a

2019-07-21 06:14发布

问题:

I have found out in the answer to a previous question a way to call a function defined in a (C++) xll without registering it. I was previously using the registering infrastructure provided by XLW and I was using the XlfOper type to pass the arguments between VBA and the xll.

The c++ function goes like this:

extern "C" {
LPXLOPER EXCEL_EXPORT a_function(XlfOper arg1, XlfOper arg2);
}

Following the answer to my previous solution, I am directly declaring the function, something like that:

Declare Function an_exported_function Lib "MyDrive:\MyPath\myxll.xll"_
          Alias "a_function" (arg1 As Object, arg2 As Object) as Object

By attaching to the excel process I can see that the function is being called but I am getting garbage or null data in the arguments. This, I guess, comes from the fact that I have not told to VBA how to convert to the correct data type.

How can I correctly call an XlfOper argument? I think that calling an LPXLOPER should do the job, since xlw states the following:

It is important not to add any data members or virtual functions to this class. The design of xlw relies on the fact that class XlfOper has the same size as LPXLOPER/LPXLOPER12, this assumption allows values of those types received from Excel to be interpreted by the library as instances of XlfOper.

回答1:

After some research i have found it: Passing User-Defined Types

MSDN wrote: Many DLL functions require you to pass in a data structure by using a predefined format. When calling a DLL function from VBA, you pass a user-defined type that you have defined according to the function's requirements.

So, you need to define XlfOper data structure ;)