Advent Day 5 Ms Access Gurus

VBA, API, Get Computer Name

VBA to return Computer Name as a string. Easy to use in queries, and on forms or reports. Behind the scenes, conditional compilation is used to declare a Windows API (application programming interface) function differently depending on 32 or 64-bit, and called. In this fairly isolated case, nothing is different except addition of PtrSafe keyword.

Updating a 32-bit application to work in 64-bit?

Download Peter Cole's free API Viewer + Scanner to find problems and lookup correct syntax for API calls.
https://www.thememydatabase.co.uk/access32to64.html
it's free -- click the Download button and then click Add to Cart in the screen that pops up. There won't be a charge.

Examples

in an expression:

"Your computer name is '" & apiGetComputerName() & "'"

as a Control Source:

=apiGetComputerName()

Reference

help: GetComputerNameA function

Code

VBA7 is available for Access 2010 and greater.

'*************** Code Start *****************************************************
' Purpose  : return the computer name. uses the GetComputerNameA Windows API   
' Author   : crystal (strive4peace) 
' Return   : String
' Code List: https://msaccessgurus.com/com/code.htm
' This code: https://msaccessgurus.com/VBA/Code/API_GetComputerName.htm
' LICENSE  :
'   You may freely use and share this code, but not sell it.
'   Keep attribution. Use at your own risk.
'--------------------------------------------------------------------------------

' API Declaration

'-------------------------------------------------------------------------------- ' PtrSafe is the only thing different, in this case '... but maybe an important word to include
#If VBA7 Then Private Declare PtrSafe Function apiGetComputerName _ Lib "kernel32" Alias "GetComputerNameA" _ (ByVal lpBuffer As String, nSize As Long) _ As Long #Else ' VBA 6 or earlier Private Declare Function apiGetComputerName _ Lib "kernel32" Alias "GetComputerNameA" _ (ByVal lpBuffer As String, nSize As Long) _ As Long #End If '--------------------------------------------------------------------------------

' GetComputerName

'-------------------------------------------------------------------------------- '
Public Function GetComputerName( _ ) As String '161220 s4p Dim sBuffer As String _ , nLen As Long _ , nSize As Long nLen = 16 sBuffer = String$(nLen, 0) nSize = apiGetComputerName(sBuffer, nLen) If nSize <> 0 Then GetComputerName = Left$(sBuffer, nLen) Else GetComputerName = "" End if End Function ' '*************** Code End *******************************************************
' reference: GetComputerNameA function

Share

Share with others ... here's the link to copy:
https://msaccessgurus.com/VBA/API_GetComputerName.htm