简体   繁体   中英

Excel/VBA Environ(“username”) error

I have a spreadsheet that contains a range of model inputs that get loaded into a SQL Server database. Part of this process involves building an audit trail of who updated what and when - I record the user and machine name as well as timestamp.

Within my VBA code, I have the following:

user = VBA.environ$("username")

This is running on a Win7 machine, with Office 2013.

When I run the code, it all works fine, but when someone in production runs it (on the same machine, but they are logged in, not me), it falls over on the line above. I have used variations of the above (user = environ("username"), user = environ$("username")) but always with the same outcome - it works for me, but not for others.

Does anyone have any thoughts on how to fix this?

The environment variables are unreliable

  1. The user can edit the value to anything they want
  2. The user can delete the environment variables.

Try one of these API methods.

Option 1

Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, nSize As Long) As Long

Sub Sample()
    Dim lpBuff As String * 25
    Dim ret As Long, UserName As String

    ret = GetUserName(lpBuff, 25)
    UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)

    MsgBox UserName
End Sub

Option 2

Option Explicit

Private Declare Function GetEnvironmentVariable Lib _
"kernel32" Alias "GetEnvironmentVariableA" _
(ByVal lpName As String, ByVal lpBuffer As String, _
ByVal nSize As Long) As Long


Private Sub Sample()
    Dim strUserName As String * 255
    Dim x As Integer

    x = GetEnvironmentVariable("USERNAME", strUserName, Len(strUserName))
    If x > 0 Then
        x = InStr(strUserName, vbNullChar)
        If x > 0 Then
            MsgBox (Left$(strUserName, x - 1))
        Else
            MsgBox (Left$(strUserName, x))
        End If
    End If
End Sub

Here you are:

Sub Test()
    With CreateObject("WScript.Network")
        Debug.Print .UserName
        Debug.Print .ComputerName
        Debug.Print .UserDomain
    End With
End Sub

我总是使用Application.UserName因为它总是总是更好environ$("username")可以给您类似“ john〜smith”的东西,而Application.UserName可以给您“ John Smith”

I always use

Environ("USERPROFILE")

But generally speaking I need to reference that person's desktop quite a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM