Home > Articles > Home & Office Computing > Microsoft Applications

Understanding and Using Windows API Calls for Excel Programming

  • Print
  • + Share This
When developing Excel-based applications, you can get most things done by using the Excel object model. After reading this sample book chapter, you will be comfortable about including API calls in your applications, understand how they work, and be able to modify them to suit your needs.
This chapter is from the book

In the Programming with the Windows API chapter of our Excel 2002 VBA Programmers Reference, we approached the subject of using Windows API calls by explaining how to locate the definitions for various functions on the MSDN Web site and translate those functions for use in VBA. The idea was to enable readers to browse through the API documentation and use anything of interest they found.

In reality, extremely few people use Windows API calls in that manner; indeed, trying to include previously unexplored API calls in our Excel applications is very likely to result in a maintenance problem, because it's doubtful that another developer will understand what we were trying to do. Instead, most of us go to Google and search the Web or the newsgroups for the answer to a problem and find that the solution requires the use of API calls. (Searching Google for "Excel Windows API" results in more than 200,000 Web pages and 19,000 newsgroup posts.) We copy the solution into our application and hope it works, usually without really understanding what it does. This chapter shines a light on many of those solutions, explaining how they work, what they use the API calls for, and how they can be modified to better fit our applications. Along the way, we fill in some of the conceptual framework of common Windows API techniques and terminology.

By the end of the chapter, you will be comfortable about including API calls in your applications, understand how they work, accept their use in the example applications we develop in this book and be able to modify them to suit your needs.

Overview

When developing Excel-based applications, we can get most things done by using the Excel object model. Occasionally, though, we need some information or feature that Excel doesn't provide. In those cases, we can usually go directly to the files that comprise the Windows operating system to find what we're looking for. The first step in doing that is to tell VBA the function exists, where to find it, what arguments it takes and what data type it returns. This is done using the Declare statement, such as that for GetSystemMetrics:

Declare Function GetSystemMetrics Lib "user32" _
         (ByVal nIndex As Long) As Long

This statement tells the VBA interpreter that there is a function called GetSystemMetrics located in the file user32.exe (or user32.dll, it'll check both) that takes one argument of a Long value and returns a Long value. Once defined, we can call GetSystemMetrics in exactly the same way as if it is the VBA function:

Function GetSystemMetrics(ByVal nIndex As Long) As Long
End Function

The Declare statements can be used in any type of code module, can be Public or Private (just like standard procedures), but must always be placed in the Declarations section at the top of the module.

Finding Documentation

All of the functions in the Windows API are fully documented in the Windows Development/Platform SDK section of the MSDN library on the Microsoft Web site, at http://msdn.microsoft.com/library, although the terminology used and the code samples tend to be targeted at the C++ developer. A Google search will usually locate documentation more appropriate for the Visual Basic and VBA developer, but is unlikely to be as complete as MSDN. If you're using API calls found on a Web site, the Web page will hopefully explain what they do, but it is a good idea to always check the official documentation for the functions to see whether any limitations or other remarks may affect your usage.

Unfortunately, the MSDN library's search engine is significantly worse than using Google to search the MSDN site. We find that Google always gives us more relevant pages than MSDN's search engine. To use Google to search MSDN, browse to http://www.google.com and click the Advanced Search link. Type in the search criteria and then in the Domain edit box type msdn.microsoft.com to restrict the search to MSDN.

Finding Declarations

It is not uncommon to encounter code snippets on the Internet that include incorrect declarations for API functions—such as declaring an argument's data type as Integer or Boolean when it should be Long. Although using the declaration included in the snippet will probably work (hopefully the author tested it), it might not work for the full range of possible arguments that the function accepts and in rare cases may cause memory corruption and data loss. The official VBA-friendly declarations for many of the more commonly used API functions can be found in the win32api.txt file, which is included with a viewer in the Developer Editions of Office 97–2002, Visual Basic 6 and is available for download from http://support.microsoft.com/?kbid=178020. You'll notice from the download page that the file hasn't been updated for some time. It therefore doesn't include the declarations and constants added in recent versions of Windows. If you're using one of those newer declarations, you'll have to trust the Web page author, examine a number of Web pages to check that they all use the same declaration or create your own VBA-friendly declaration by following the steps we described in the Excel 2002 VBA Programmers Reference.

Finding the Values of Constants

Most API functions are passed constants to modify their behavior or specify the type of value to return. For example, the GetSystemMetrics function shown previously accepts a parameter to specify which metric we want, such as SM_CXSCREEN to get the width of the screen in pixels or SM_CYSCREEN to get the height. All of the appropriate constants are shown on the MSDN page for that declaration. For example, the GetSystemMetrics function is documented at http://msdn.microsoft.com/library/en-us/sysinfo/base/getsystemmetrics.asp and shows more than 70 valid constants.

Although many of the constants are included in the win32api.txt file mentioned earlier, it does not include constants added for recent versions of Windows. The best way to find these values is by downloading and installing the core Platform SDK from http://www.microsoft.com/msdownload/platformsdk/sdkupdate/. This includes all the C++ header files that were used to build the DLLs, in a subdirectory called \include. The files in this directory can be searched using normal Windows file searching to find the file that contains the constant we're interested in. For example, searching for SM_CXSCREEN gives the file winuser.h. Opening that file and searching within it gives the following lines:

#define SM_CXSCREEN       0
#define SM_CYSCREEN       1

These constants can then be included in your VBA module by declaring them as Long variables with the values shown:

Const SM_CXSCREEN As Long = 0
Const SM_CYSCREEN As Long = 1

Sometimes, the values will be shown in hexadecimal form, such as 0x8000, which can be converted to VBA by replacing the 0x with &h and adding a further & on the end, such that

#define KF_UP        0x8000

becomes

Const KF_UP As Long = &h8000&

Understanding Handles

Within VBA, we're used to setting a variable to reference an object using code like

Set wkbBackDrop = Workbooks("Backdrop.xls")

and releasing that reference by setting the variable to Nothing (or letting VBA do that for us when it goes out of scope at the end of the procedure). Under the covers, the thing that we see as the Backdrop.xls workbook is just an area of memory containing data structured in a specific way that only Excel understands. When we set the variable equal to that object, it is just given the memory location of that data structure. The Windows operating system works in a very similar way, but at a much more granular level; almost everything within Windows is maintained as a small data structure somewhere. If we want to work with the item that is represented by that structure (such as a window), we need to get a reference to it and pass that reference to the appropriate API function. These references are known as handles and are just ID numbers that Windows uses to identify the data structure. Variables used to store handles are usually given the prefix h and are declared As Long.

When we ask for the handle to an item, some functions—such as FindWindow—give us the handle to a shared data structure; there is only one data structure for each window, so every call to FindWindow with the same parameters will return the same handle. In these cases, we can just discard the handle when we're finished with it. In most situations, however, Windows allocates an area of memory, creates a new data structure for us to use and returns the handle to that structure. In these cases, we must tidy up after ourselves, by explicitly telling Windows that we've finished using the handle (and by implication, the memory used to store the data structure that the handle points to). If we fail to tidy up correctly, each call to our routine will use another bit of memory until Windows crashes—this is known as a memory leak. The most common cause of memory leaks is forgetting to include tidy-up code within a routine's error handler. The MSDN documentation will tell you whether you need to release the handle and which function to call to do it.

Encapsulating API Calls

GetSystemMetrics is one of the few API calls that can easily be used in isolation—it has a meaningful name, takes a single parameter, returns a simple result and doesn't require any preparation or cleanup. So long as you can remember what SM_CXSCREEN is asking for, it's extremely easy to call this function; GetSystemMetrics(SM_CXSCREEN) gives us the width of the screen in pixels.

In general practice, however, it is a very good idea to wrap your API calls inside their own VBA functions and to place those functions in modules dedicated to specific areas of the Windows API, for the following reasons:

  • The VBA routine can include some validity checks before trying to call the API function. Passing invalid data to API functions will often result in a crash.

  • Most of the textual API functions require string variables to be defined and passed in, which are then populated by the API function. Using a VBA routine hides that complexity.

  • Many API functions accept parameters that we don't need to use. A VBA routine can expose only the parameters that are applicable to our application.

  • Few API functions can be used in isolation; most require extra preparatory and clean up calls. Using a VBA routine hides that complexity.

  • The API declarations themselves can be declared Private to the module in which they're contained, so they can be hidden from use by other developers who may not understand how to use them; their functionality can then be exposed through more friendly VBA routines.

  • Some API functions, such as the encryption or Internet functions, require an initial set of preparatory calls to open resources, a number of routines that use those resources and a final set of routines to close the resources and tidy up. Such routines are ideally encapsulated in a class module, with the Class_Initialize and Class_Terminate procedures used to ensure the resources are opened and closed correctly.

  • By using dedicated modules for specific areas of the Windows API, we can easily copy the routines between applications, in the knowledge that they are self-contained.

When you start to include lots of API calls in your application, it quickly becomes difficult to keep track of which constants belong to which functions. We can make the constants much easier to manage if we encapsulate them in an enumeration and use that enumeration for our VBA function's parameter, as shown in Listing 9-1. By doing this, the applicable constants are shown in the Intellisense list when the VBA function is used, as shown in Figure 9-1. The ability to define enumerations was added in Excel 2000.

Listing 9-1 Encapsulating the GetSystemMetrics API Function and Related Constants

'Declare all the API-specific items Private to the module
Private Declare Function GetSystemMetrics Lib "user32" _
    (ByVal nIndex As Long) As Long
Private Const SM_CXSCREEN As Long = 0
Private Const SM_CYSCREEN As Long = 1

'Wrap the API constants in a public enumeration,
'so they appear in the Intellisense dropdown
Public Enum SystemMetricsConstants
 smScreenWidth = SM_CXSCREEN
 smScreenHeight = SM_CYSCREEN
End Enum

'Wrapper for the GetSystemMetrics API function,
'using the SystemMetricsConstants enumeration
Public Function SystemMetrics( _
    ByVal uIndex As SystemMetricsConstants) As Long

 SystemMetrics = GetSystemMetrics(uIndex)
End Function

Figure 9.1Figure 9-1 By Using the Enumeration, the Relevant Constants Appear in the Intellisense Drop-Down

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020