从 VBA 调用 xll UDF

Calling an xll UDF from VBA

我想从 VBA 调用我的用户定义函数之一。

我的用户定义函数是用 C++ 声明的:

XLOPER12*WINAPI HelloWorld()noexcept{
    THROWS();
    static XLOPER12 res=[](){
        static std::array<wchar_t,13>str={
            11,'H','e','l','l','o',' ','W','o','r','l','d','[=11=]'};
        XLOPER12 tmp;
        tmp.xltype=xltypeStr;
        tmp.val.str=str.data();
        return tmp;}();
    return &res;}

这是该字段中真实函数的简化版本,它可以是 return 字符串或双精度数组或偶数数组。当然在这里我只是 returning 一个字符串但是这将我的 UDF 的 return 类型限制为 LPXLOPER12.

我可以使用 xlfRegister 成功注册我的函数,指定 pxTypeText"U$"。然后我可以从 Excel:

调用我的 UDF
=HelloWorld()

而且有效!


如果我尝试按照建议从 VBA 调用我的函数 here:

Sub macro_test()
    Dim hw As Variant
    hw = Application.Run("D:\Path\MyAddIn.xll!HelloWorld")
End Sub

我从 Application.run 收到一条错误消息:

Run-time error '1004': Application-defined or object-defined error


如果我尝试按照建议从 VBA 调用我的函数 here:

Private Declare PtrSafe Function HelloWorld Lib "C:\Path\MyAddIn.xll" () As Variant

Sub macro_test()
    Dim hw As Variant
    hw = HelloWorld()
End Sub

我得到一个空结果而不是"Hello World"


我做错了什么?

杂项资料:

如果您的 XLL 已加载并且其 UDF 已注册,因此单元格中的=HelloWord() 可以正常工作,那么您应该可以像这样从 VBA 调用它(除非无参数存在问题字符串函数)

var=Application.run("HelloWorld")

您也可以使用评估

var=Application.Evaluate("=HelloWorld()")

我像这样测试了我的 REVERSE.TEXT XLL 函数并且它工作正常。

Sub testing()
Dim var As Variant
var = Application.Run("REVERSE.TEXT", "Charles")
var = Application.Evaluate("=REVERSE.TEXT(""Charles"")")
End Sub

Reverse.Text使用UQQ$注册(有2个参数,文本和字符数)