Appendix B. Getting the Installed Printers

As discussed in Chapter 10, the ActivePrinter property can set the active printer. This raises the issue of how to determine the installed printers on a given computer. Unfortunately, VBA does not seem to provide a way to do this. (Visual Basic has a Printers collection, but Visual Basic for Applications does not.)

In this appendix, we describe a program for getting this printer information. As mentioned in Chapter 10, this program uses the Windows API. To use this program, just type it into your own code, as described here.

The first step is to declare some special constants in the Declarations section of a standard module:

Public Const KEY_ENUMERATE_SUB_KEYS = &H8
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const SUCCESS = 0&

Next, we need to declare a user-defined type. We have not discussed these data structures in this book, but a user-defined type is essentially just a custom data type. Enter the following code into the Declarations section:

Type FILETIME
  dwLowDateTime As Long
  dwHighDateTime As Long
End Type

Then we need to declare three API functions. As you can see, these are relatively complicated functions as VBA functions go, but not as API functions go. Enter the following in the Declarations section:

Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias _ "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As _ String, ByVal ulOptions As Long, ByVal samDesired As _ Long, phkResult As Long) As Long Declare Function ...

Get Writing Excel Macros with VBA, 2nd Edition 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.