Chapter 27: Using the Windows Application Programming Interface
949
Dim strMyString As String
strMyString = String$(20,” “)
The preceding code fills the fixed-width string variable strMyString with 20 spaces. You can
achieve the same result by declaring the string with the number of characters already allocated:
Dim strMyString * 20
Caution
If you don’t allocate enough space for an API function to write a string, it could end up writing over another
application’s data, causing an error. It’s very difficult to know how many characters an API will accept, so a
safe way to declare your string variables is to allocate 255 characters to string variables. Most functions will
not pass a string larger than 255 characters.
As DataType
Any API call that is a function returns a value. A subroutine does not. The value returned by a
function is usually a value that you use in your application, or it’s an error number. For example,
many functions return zero, or ERROR_SUCCESS if the function completes successfully. In this
case, if the value returned is not zero (indicating that the API call failed to execute properly), you
should provide an error-handling routine to deal with the function’s failure.
Other functions, such as GetPrivateProfileStringA, return a numeric value indicating the
number of characters copied into a string buffer. Therefore, if GetPrivateProfileStringA
completes successfully, you use its return value and the Left$() function to extract the returned
string from a string buffer.
StringVar = Left$(StringBuffer, ReturnValue)
If the value returned by GetProfileStringA is 0 , of course, it means that no string was found
in the .ini file.
The data type specified for the return value must be compatible with the data type specified in the
API function’s documentation.
Wrapper functions
You rarely directly program API functions. API calls frequently require complicated arguments,
and the values returned by API functions most often require interpretation before they can be used.
Many developers use wrapper functions to resolve these issues. A wrapper function is a simple VBA
procedure that provides the API call with all the parameters it needs, as well as converting the val-
ues returned by the API function to a format the application can use. Your VBA code calls the
wrapper function, which, in turn, calls the API function. The wrapper function returns the trans-
formed value provided by the API function.