从Excel Vba中调用DLL函数调用

我试图从Excel中的VBA DLL调用函数。

我的Excel VBAmacros看起来像这样:

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 

现在,当我从“= TestDll(3.0)”这样的Excel单元格调用它时,它不起作用。 我在即时窗口中看到“开始”string,但没有别的。 这就像一个错误发生在“TestFunction1”被调用时。 Excel显示“#VALUE!” 在牢房里。

我也可以在debugging器中设置断点,但是当我到达TestFunction1调用时,它就结束了。 没有我能find的错误信息。

我的问题是,我怎么debugging呢? 我没有收到任何错误消息。 它根本不起作用。 我怎样才能找出发生了什么问题?

您在debugging语句中使用的variables有错误,因此UDF失败。 rest很好。 实际上,你需要将r转换为string,或者在debugging语句中使用&来连接。

编辑:包括error handling程序。

 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