Tutorial :Environ Function code samples for VBA



Question:

I am looking for some information or code samples for the Environ Function in VBA to grab the username on the current system.


Solution:1

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set  

If you wanted to get the username, you would do:

Environ("username")  

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")  

References


Solution:2

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")  

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()          Dim strVar As String          Dim i As Long          For i = 1 To 255              strVar = Environ$(i)              If LenB(strVar) = 0& Then Exit For              Debug.Print strVar          Next      End Sub

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »