views:

1951

answers:

6

I found this via google: http://www.mvps.org/access/api/api0008.htm is this the best way to do it?

+5  A: 

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

Ken
+1  A: 

Alernative way to do that - probably API you mention is the good way to get username.

For Each strComputer In arrComputers
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
        For Each objItem in colItems
        Wscript.Echo "UserName: " & objItem.UserName & " is logged in at computer " & strComputer
Next
bugBurger
+1  A: 

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

bobwienholt
You'll need to add a reference to the Microsoft Scripting Runtime to your project. (scrrun.dll)
DMKing
You don't have to if you use CreateObject(). The code above will work without a reference.
bobwienholt
You do have to have the WshNetwork variable defined as a generic object, instead of as the FSO's native data type (whatever that is -- I never use the FSO except with late binding, so don't know any of its data types at all).
David-W-Fenton
A: 

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
Knox
+1  A: 

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.

Joe
A: 

I tried to reproduce steps mentioned here(answer by ken) but I was not able to change any value of the Environ object. The only way to do this in straight VBA is then the one proposed here(answer by knox) and I cannot understand why this answer was downgraded!

Philippe Grondier