Environ Function code samples for VBA

前端 未结 3 1483
死守一世寂寞
死守一世寂寞 2020-11-30 04:54

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

相关标签:
3条回答
  • 2020-11-30 05:31

    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

    • Microsoft | Office VBA Reference | Language Reference VBA | Environ Function
    • Microsoft | Office Support | Environ Function
    0 讨论(0)
  • 2020-11-30 05:32

    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
    0 讨论(0)
  • 2020-11-30 05:36

    Some time when we use Environ() function we may get the Library or property not found error. Use VBA.Environ() or VBA.Environ$() to avoid the error.

    0 讨论(0)
提交回复
热议问题