Accessing Functions in a DLL

Before you can call a function in a DLL from VBA, you must provide VBA with information about where that function is and how to call it. There are two ways to do this: by setting a reference to the DLL's type library, or by using a Declare statement in a module.

Setting a reference to a DLL's type library is the easiest way to work with functions in the DLL. When you set the reference, you can call the DLL function as though it were part of your project. There are a couple of caveats, however. First, setting references to multiple type libraries can affect your application's performance. Second, not all DLLs provide type libraries. Although you can set a reference to a DLL that does not provide a type library, you cannot call functions in that DLL as though they were part of your project.

Note   The DLLs that form the Microsoft® Windows® API do not provide type libraries, so you cannot set references to them and call their functions. To call a function in the Windows API, you must include a Declare statement in the Declarations section of a module in your project. A Declare statement is a definition that tells VBA where to find a particular DLL function and how to call it. The easiest way to add a Declare statement to your code is to use the API Viewer add-in, which contains Declare statements for most of the functions in the Windows API, as well as the constants and type definitions that some functions require.

See Also

API Basics | What Is an API? | Why Use VBA to Call the Windows API? | API Resources | Anatomy of a Declare Statement | Constants and User-Defined Types | Understanding Handles