Solved UserName for 64-bit (1 Viewer)

Kayleigh

Member
Local time
Today, 11:09
Joined
Sep 24, 2020
Messages
706
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!
 

The_Doc_Man

Immoderate Moderator
Staff member
Local time
Today, 06:09
Joined
Feb 28, 2001
Messages
27,001
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.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 19:09
Joined
May 7, 2009
Messages
19,175
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

Top Bottom