简体   繁体   English

从Excel Vba解决DLL函数调用问题

[英]Troubleshooting DLL function call from Excel Vba

I'm trying to call a function from a DLL from VBA in Excel. 我正在尝试从Excel中的VBA调用DLL中的函数。

My Excel VBA macro looks like this: 我的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

Now when I call it from an Excel cell with something like "=TestDll(3.0)", it doesn't work. 现在,当我从Excel单元格中调用“= TestDll(3.0)”之类的东西时,它不起作用。 I see the "Start" string in the immediate window, but nothing else. 我在即时窗口中看到“开始”字符串,但没有别的。 It's like an error is happening exactly when "TestFunction1" is being called. 这就像正在调用“TestFunction1”时发生的错误。 Excel displays "#VALUE!" Excel显示“#VALUE!” in the cell. 在牢房里。

I can also set a breakpoint in the debugger, but when I get to the TestFunction1 call, it just ends. 我也可以在调试器中设置一个断点,但是当我进入TestFunction1调用时,它就结束了。 There is no sort of error message I can find. 我找不到任何错误消息。

My question is, how do I debug this? 我的问题是,我该如何调试? I'm not getting any error message. 我没有收到任何错误消息。 It simply doesn't work. 它根本不起作用。 How can I figure out what is going wrong? 我怎么能弄清楚出了什么问题?

The variable which you are using in debug statement,has an error and hence the UDF fails. 您在调试语句中使用的变量有错误,因此UDF失败。 Rest is fine. 休息很好。 Actually you need to convert r to string or use & for concatenation in your debug statement. 实际上你需要将r转换为字符串或在调试语句中使用&进行连接。

Edit: to include error handler. 编辑:包含错误处理程序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM