< Day Day Up > |
As far as your other code is concerned, there's no difference between a procedure declared in VBA (using the Sub or Function keywords) and one declared using the Declare keyword. Here's a VBA function that gets the computer name using the API call just declared: Function GetThisComputerName() As String ' Retrieve the name of this computer using ' the Windows API Dim strName As String Dim lngChars As Long Dim lngRet As Long strName = Space(255) lngChars = 255 lngRet = GetComputerName(strName, lngChars - 1) If lngChars > 0 Then GetThisComputerName = Left(strName, lngChars) Else GetThisComputerName = "Unable to retrieve name." End If End Function Although GetComputerName is just another function as far as this code is concerned, there are two other points to be aware of. First, you need to be careful when passing String arguments to API calls, because the API definition of a string differs from the VBA definition. API strings are a fixed length, whereas VBA strings are variable. So, when you're passing in a string to an API call, you pass a string that you've initialized to a specified length, and another variable to tell the API how long the string is. The API call passes back, in the second variable, the number of characters that it actually used in the fixed-length string. TIP The VBA Space() function returns a string consisting of the specified number of spaces an ideal way to initialize a string argument for an API call. The API needs one extra position in the string to hold its own end-of-string marker. That's why, when you pass in a 255-character long string, you must tell the API that it has 254 characters to work with. When the string comes back, you can use the VBA Left function to trim off the characters past the length that the API call specified. This section of the code also indicates the second point that you need to be aware of: most API calls return zero if all is well, or a non-zero value if something went wrong. Figure 23.1 shows the result of running this function on the testbed system. Of course, on your own computer, the return value will be different. Figure 23.1. Using the Windows API to get the computer name.![]() |
< Day Day Up > |