3

I know there are at least 2 ways of retrieving the username in an Access application.

You can use the environ function:

environ("username")

And you can use GetUsername in advapi32.dll

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

s = String(l, Chr(32))
GetUserName s, l
username = Left$(s, l - 1)

Which one of the above methods is the safest to use? And why?

Perhaps some background info, the applications are used both on the local computers and remote desktops.

Erik A
  • 31,639
  • 12
  • 42
  • 67
SouthL
  • 175
  • 2
  • 12

2 Answers2

6

As Simon has said, Environ variables are open to manipulation, however some people also like to avoid the api calls, if this is the case then this is a simple to follow alternative:

Public Function GetUser() As String

    Dim WNet As Object

    Set WNet = CreateObject("WScript.Network")

    GetUser = WNet.UserName

    Set WNet = Nothing

End Function
Matt Donnan
  • 4,933
  • 3
  • 20
  • 32
  • 1
    +1 except I would skip the `Set Nothing` statement because WNet will be destroyed when it goes out of scope. – JimmyPena Jan 24 '12 at 16:40
2

Environment variables can be set and unset by anyone, go missing and whatnot, and these cases tend to be difficult to reproduce if anyone even thinks of it as a source of errors.

I'd definitely go with advapi.

Simon Richter
  • 28,572
  • 1
  • 42
  • 64