Declare and Use DLL Functions

Use the API Viewer (Figure 23-1) or open WIN32API.TXT in Notepad to get the declarations of DLL functions you want to use in Visual Basic. The declaration tells Visual Basic how to find the function and what arguments the function expects. For example, the declaration for the Sleep function looks like this:

' Module level.
Public Declare Sub Sleep Lib "kernel32" _
  (ByVal dwMilliseconds As Long)
Use the API Viewer to hunt for DLL functions

Figure 23-1. Use the API Viewer to hunt for DLL functions

That means the Sleep function is found in kernel32.dll, takes a single long-integer argument, and doesn’t return a value. Once you declare the function, you can use it in code just like any other procedure:

Sub Pause(  )
    ' Pause 1/2 second.
    Sleep 500
End Sub

In Visual Basic terminology, Sleep is a Sub, not a function. However, most DLLs are written in C, which doesn’t use that word. In C, all procedures are functions; functions that don’t return values are called void functions .

However, most DLL functions do return a value, and that value usually indicates whether the function succeeded. If a function returns 0, the function failed. Any other value indicates success. For example, the following code plays boing.wav; if the sound can’t play, the code displays a message in the Immediate window:

Public Declare Function sndPlaySound Lib "winmm.dll" Alias _ "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.