How to use Win32 VBA API

Win32 VBA API usage is straight forward for a simple API call and many common basic API calls are simple.

First you have to declare the API in a Module. This involves finding the API you are looking for and then copying it to a Module.

For example, if you wany to retrieve the username of the logged in user you would search for "API  get username" (without the quotes) or something similar related to what you want the API to do...

In this case you would quickly find results for an API called getuername. Copy its Declare statement to a Module. For readability and orgainizational purposes if you're will be using it in various places use a separate Module dedicared to APIs.  You then paste the Declare as follows...


Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long


If you are using it in places other than the Module where you place the Declare be sure the firest word of the Declare is "Public" and not "Private". A private declaced API can only be called from within the same Module as the Declare.

You can see in this API that there are 2 variables. The first is lpBuffer which is a buffer (placeholder) for the API to the username. The second is nSize, which is the size or length of this buffer.

You have to fill the variable you pass to the API and have a Return variable as Long. you can see this in the code below...

Sub User()

Dim res As Long
Dim MyBuff As String * 256
Dim MySize As Long

MySize = 256
res = GetUserName(MyBuff, MySize)
If res <> 0 Then
    MsgBox Left$(MyBuff, InStr(1, MyBuff, vbNullChar) - 1)
Else
    MsgBox "Error, Not logged in"
End If


This site is powered by Site Build It!. If you enjoy it, please check out the
Site Build It homepage
 to learn more and on how to build a success-guaranteed site with no technical skills.

Custom Search






Return from Win32 VBA API to VBA Code Samples

Return to our Homepage