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 incident, nothing is different except addition of PtrSafe keyword.
Download Peter Cole's free Scanner and Viewer (comes with 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.
Using conditional compilation, declare the Windows API GetComputerNameA function depending on 64-bit or 32-bit, under VBA7 or earlier, using an #If statement block that evaluates operating system information. In code, the API is then referred to as apiGetComputerName, which is used by the VBA GetComputerName function to return a string with the computer name.
Gets the NetBIOS name of the local computer. To get DNS information, use GetComputerNameExA
API declarations must be made before any procedures are defined in the module.
'*************** 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 *******************************************************