对来自 Excel Vba 的 DLL 函数调用进行故障排除

Troubleshooting DLL function call from Excel Vba

我正在尝试从 Excel 中的 VBA 的 DLL 调用函数。

我的 Excel VBA 宏如下所示:

Declare PtrSafe Function TestFunction1 Lib "mylib.dll" (ByVal k As Double) As Double

Public Function TestDll(k As Double) As Double
    Debug.Print ("Start")

    Dim r As Double
    r = TestFunction1(k)

    Debug.Print ("Got result of " + r)
    Debug.Print ("Done")

    TestDll = r
End Function

现在,当我从 Excel 单元格中使用类似“=TestDll(3.0)”的内容调用它时,它不起作用。我在立即 window 中看到了 "Start" 字符串,但没有别的。就像在调用 "TestFunction1" 时发生错误一样。 Excel 显示“#VALUE!”在单元格中。

我也可以在调试器中设置断点,但是当我到达 TestFunction1 调用时,它就结束了。我找不到任何类型的错误消息。

我的问题是,我该如何调试它?我没有收到任何错误消息。它根本行不通。我怎样才能找出问题所在?

您在调试语句中使用的变量有错误,因此 UDF 失败。 休息很好。实际上,您需要将 r 转换为字符串或在调试语句中使用 & 进行连接。

编辑:包括错误处理程序。

Public Function TestDll(k As Double) As Double
    Debug.Print ("Start")

    Dim r       As Double

    '/ Add a error handler
    On Error GoTo errHandler
    '/ Assuming that your testfunction will return 10*parameter
    r = k * 10


    '/ The variable which you are returning,has a error and hence the UDF fails.
    '/ Rest is fine. Here you will get type mismatch error.
    Debug.Print ("Got result of " + r)

    '/ Actually you need to convert it to string or use `&` for concatenation
    Debug.Print ("Got result of " + CStr(r))

    '/ or
    Debug.Print ("Got result of " & r)


    Debug.Print ("Done")

    TestDll = r

errHandler:
    If Err.Number <> 0 Then
        '/ Error trapped and you get actual error desc and number.
        MsgBox Err.Description, vbCritical, Err.Number
    End If

End Function