Access Windows APIs from VBA

AutoCAD ActiveX

 
Access Windows APIs from VBA
 
 
 

The Windows® API procedures are available to most Windows applications. These procedures allow you to expand the capabilities of your application.

Through the Windows APIs you can obtain information about the current system, such as which other programs are installed or running on the system, where information is located on a system, and what the current control settings are for the system. You can also access joystick, multimedia, and sound controls. These tasks represent but a few of the many capabilities provided by the Windows APIs.

To use a Windows API, you must first declare the API in your application. This is done with the Declare statement. The Declare statement requires several pieces of information:

  • The name of the dynamic link library (DLL) containing the procedure you want to use
  • The name of the procedure as it appears in the DLL
  • The name of the procedure as you want to use it in your application
  • The parameters the procedure expects to receive
  • The return value data type (if the procedure you are calling is a function)

You can place the Declare statement in any of your VBA modules. If you place it in a standard module, the procedure will be available to any module in your application, unless you limit its scope by using the keyword Private. If you place the Declare statement in a class or form module, the procedure will only be available in that module. Once a procedure has been declared, you can call that procedure as you would any other procedure in your application.

Getting a Declare statement just right is a difficult skill to learn. Getting a Declare statement wrong is easy, but it often comes with dire consequences. Be sure to save any information in active applications before you try out a new Declare statement.

To help you with your Declare statements, Microsoft provides a file listing of many of the declarations most commonly used. The file is called Win32api.txt and comes with Visual Basic 6 and Office. You can search this file for the procedure you need and copy the Declare statement provided into your code.

The Microsoft VBA documentation contains more information on the Declare statement and an example of its use. The Microsoft Windows API Reference is available as part of the Microsoft Developer Network CD subscription and provides a reference to all the available procedures in the Windows APIs. Dan Appleman's book Visual Basic Programmer's Guide to the Win32 API is also an excellent resource directed at the Visual Basic 6 programmer.