Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubleshooting DLL function call from Excel Vba

Tags:

I'm trying to call a function from a DLL from VBA in Excel.

My Excel VBA macro looks like this:

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. 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. Excel displays "#VALUE!" in the cell.

I can also set a breakpoint in the debugger, but when I get to the TestFunction1 call, it just ends. 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?

like image 613
carrie88 Avatar asked Sep 05 '16 00:09

carrie88


1 Answers

The variable which you are using in debug statement,has an error and hence the UDF fails. Rest is fine. Actually you need to convert r to string or use & for concatenation in your debug statement.

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
like image 138
teddy2 Avatar answered Sep 25 '22 16:09

teddy2