Using the Declare Statement

Before you can call a DLL function from Visual Basic, you must use the Declare statement to identify the function, the name of the DLL where it is located, and its argument types. Once the function is declared in a Visual Basic module, you can call it just as if it were part of your code.

For example, the following C-language function calculates the circumference of a circle given the circle's radius:

double WINAPI DoubleArg(double dRadius)
{
    return dRadius * 2 * 3.14159;
}

In Windows 95 and Windows NT, DLL functions use the __stdcall calling convention. The examples in this chapter were written to run on 32-bit Microsoft Windows (Win32).

The _export keyword has been replaced by __declspec(dllexport). If you use __declspec(dllexport) without also exporting each function via the .DEF file, you will find that Visual C++ has decorated the names of all your functions. Export each function via the .DEF file to prevent this. Win32 includes a predefined constant WINAPI that contains the __stdcall directive. Our code examples will make use of this shortcut.

This Visual Basic code uses the DoubleArg C function to display a table of circumference values:

Declare Function DoubleArg Lib "debug\ADVDLL.DLL" _
    (ByVal radius As Double) As Double

Sub CircumferenceTable()
    Dim i As Double

    Worksheets(1).Activate
    Range("a1:b11").Clear
    Cells(1, 1) = "Radius"
    Cells(1, 2) = "Circumference"
    For i = 1 To 10
        Cells(i + 1, 1) = i
        Cells(i + 1, 2) = DoubleArg(i)
    Next
    Columns("a:b").AutoFit
End Sub

The Declare statement uses the ByVal keyword because the argument is passed by value. DLL functions declared as public functions in a Visual Basic module can be called from any Visual Basic module in the workbook, but cannot be called from an XLM macro sheet or worksheet. Public functions are those declared without the Private keyword (or explicitly declared with the Public keyword). If you declare the DLL function as Private, you can call the function only from the Visual Basic module where it is declared. Visual Basic loads a DLL the first time a declared function in the DLL runs, and the DLL remains loaded until you close the workbook that contains the Visual Basic module.