Solved UserName for 64-bit

Kayleigh

Member
Local time
Today, 07:49
Joined
Sep 24, 2020
Messages
709
Hi,
Would anyone be able to help me with re-writing this bit of code so it works on both 32-bit and 64-bit machines. It will currently not run on my 64-bit processor...
Code:
Option Compare Database
Option Explicit

'Return computer user name

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

Function UserName() As String
' Returns the network login name
    Dim lngLen As Long, lngX As Long
    Dim strUserName As String
    strUserName = String$(254, 0)
    lngLen = 255
    lngX = apiGetUserName(strUserName, lngLen)
    If lngX <> 0 Then
        UserName = left$(strUserName, lngLen - 1)
    Else
        UserName = ""
    End If
End Function

Thank you!
 
Yes but I suggest you scrap that code and use the much simpler WScript alternative that works in both bitnesses.
Anyway, for both sets of code, see
 
Last edited:
First thing to check is whether advapi32.dll exists on your 64-bit machine. Probably in the windows folder or the windows32 folder. If it does, then the next thing....

I think the only declaration you need to change is this one:

Code:
Private Declare PtrSafe Function apiGetUserName Lib "advapi32.dll" Alias _
...

EDIT: I see that Colin posted just before I did. His code and suggestions regarding security are usually pretty good. So even if my answer looks simple enough, his might work more reliably.
 
there is VBA function equivalent to your code:

Environ$("username")

doesn't matter if run on x32 or x64 msa.
 

Users who are viewing this thread

Back
Top Bottom