VBA 的环境函数代码示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/935160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:48:19  来源:igfitidea点击:

Environ Function code samples for VBA

vbaenvironment-variables

提问by gary A.K.A. G4

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

我正在为EnvironVBA 中的函数寻找一些信息或代码示例,以获取当前系统上的用户名。

回答by Eric

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

Environ()为您提供任何环境变量的值。这些可以通过在命令提示符中执行以下命令来找到:

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

参考

回答by Oorang

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

正如埃里克所暗示的那样,您可以像这样使用带有 ComputerName 参数的环境:

MsgBox Environ("USERNAME")

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

一些可能对您有所帮助的其他信息:

  1. The arguments are notcase 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 andthe value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
  1. 参数区分大小写。
  2. Environ 函数有一个执行速度稍快的字符串版本。要调用它,请使用美元符号。(例如:Environ$("username"))这将为您带来小的性能提升。
  3. 您可以使用此功能检索所有系统环境变量。(不仅仅是用户名。)一个常见的用途是获取“ComputerName”值以查看用户从哪台计算机登录。
  4. 我不建议在大多数情况下使用它,但偶尔知道您也可以使用index访问变量会很有用。如果使用此语法,则返回参数名称值。通过这种方式,您可以枚举所有可用的变量。有效值为 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

回答by vanidasan

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.

有时当我们使用Environ()函数时,我们可能会遇到未找到库或属性的错误。使用VBA.Environ()VBA.Environ$()来避免错误。