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

car*_*e88 5 excel vba dllimport

我正在尝试从 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
Run Code Online (Sandbox Code Playgroud)

现在,当我从 Excel 单元格中使用“=TestDll(3.0)”之类的内容调用它时,它不起作用。我在即时窗口中看到“开始”字符串,但没有其他内容。就好像在调用“TestFunction1”时发生了错误。Excel 显示“#VALUE!” 在单元格中。

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

我的问题是,我该如何调试?我没有收到任何错误消息。它根本行不通。我怎样才能弄清楚出了什么问题?

ted*_*dy2 4

您在调试语句中使用的变量有错误,因此 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
Run Code Online (Sandbox Code Playgroud)

  • @teddy2“错误”部分正是我所需要的!我现在有一条实际的错误消息要继续,希望我可以从这里得到它。谢谢x1000!(我本来会投票给你,但显然我不能?) (2认同)