Getting the currently logged-in windows user

You could also use Environ$ but the method specified by the question is better. Users/Applications can change the environment variables.


I generally use an environ from within VBA as in the following. I haven't had the problems that Ken mentions as possibilities.

Function UserNameWindows() As String
    UserNameWindows = VBA.Environ("USERNAME") & "@" & VBA.Environ("USERDOMAIN")
End Function

Lots of alternative methods in other posts, but to answer the question: yes that is the best way to do it. Faster than creating a COM object or WMI if all you want is the username, and available in all versions of Windows from Win95 up.


You could also do this:

Set WshNetwork = CreateObject("WScript.Network")
Print WshNetwork.UserName

It also has a UserDomain property and a bunch of other things:

http://msdn.microsoft.com/en-us/library/907chf30(VS.85).aspx