Appendix C. Getting the Installed Printers

As discussed in Chapter 11, The Application Object, the ActivePrinter property can be used to 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, I describe a program for getting this printer information. As mentioned in Chapter 11, this program uses the Windows API. To use this program, just type it into your own code, as described next.

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, I need to declare a user–defined type. I 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 I 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) ...

Get Writing Word Macros, Second 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.