locked
How do you find out the Windows User Name from VBA RRS feed

  • Question

  • We log onto our network with a three letter user name e.g. ADG. Can I return the user name of the person opening my Access Database with VBA?

    I want to customise the options available to the user without using the security features built into Access.

    Friday, April 28, 2006 3:39 PM

Answers

  • This will provide you with the information you desire.  I use it often in the default value of a field.

    (Environ$("Username"))

    Sunday, April 30, 2006 11:33 PM
  • Many thanks Carbo,

    Environ$("Username") returned "adg" as expected.  Thanks also Peter, but Application.CurrentUser  returned "Admin", which was not the user I was seeking this time.

    While searching on Microsoft.com I also found the below code which works, but I prefer the simple approach above.

     ' Declare for call to mpr.dll.
       Declare Function WNetGetUser Lib "mpr.dll" _
          Alias "WNetGetUserA" (ByVal lpName As String, _
          ByVal lpUserName As String, lpnLength As Long) As Long

       Const NoError = 0       'The Function call was successful

       Sub GetUserName()

          ' Buffer size for the return string.
          Const lpnLength As Integer = 255

          ' Get return buffer space.
          Dim status As Integer

          ' For getting user information.
          Dim lpName, lpUserName As String

          ' Assign the buffer size constant to lpUserName.
          lpUserName = Space$(lpnLength + 1)

          ' Get the log-on name of the person using product.
          status = WNetGetUser(lpName, lpUserName, lpnLength)

          ' See whether error occurred.
          If status = NoError Then
             ' This line removes the null character. Strings in C are null-
             ' terminated. Strings in Visual Basic are not null-terminated.
             ' The null character must be removed from the C strings to be used
             ' cleanly in Visual Basic.
             lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) - 1)
          Else

             ' An error occurred.
             MsgBox "Unable to get the name."
             End
          End If

          ' Display the name of the person logged on to the machine.
          MsgBox "The person logged on this machine is: " & lpUserName

       End Sub

     

    Wednesday, May 3, 2006 11:06 AM

All replies

  • Hi

    Access isn't my strong suite, but isn't there something like ...

    Application.CurrentUser

    that gives you the information you need?

    Peter Mo

    Saturday, April 29, 2006 5:58 PM
  • This will provide you with the information you desire.  I use it often in the default value of a field.

    (Environ$("Username"))

    Sunday, April 30, 2006 11:33 PM
  • Many thanks Carbo,

    Environ$("Username") returned "adg" as expected.  Thanks also Peter, but Application.CurrentUser  returned "Admin", which was not the user I was seeking this time.

    While searching on Microsoft.com I also found the below code which works, but I prefer the simple approach above.

     ' Declare for call to mpr.dll.
       Declare Function WNetGetUser Lib "mpr.dll" _
          Alias "WNetGetUserA" (ByVal lpName As String, _
          ByVal lpUserName As String, lpnLength As Long) As Long

       Const NoError = 0       'The Function call was successful

       Sub GetUserName()

          ' Buffer size for the return string.
          Const lpnLength As Integer = 255

          ' Get return buffer space.
          Dim status As Integer

          ' For getting user information.
          Dim lpName, lpUserName As String

          ' Assign the buffer size constant to lpUserName.
          lpUserName = Space$(lpnLength + 1)

          ' Get the log-on name of the person using product.
          status = WNetGetUser(lpName, lpUserName, lpnLength)

          ' See whether error occurred.
          If status = NoError Then
             ' This line removes the null character. Strings in C are null-
             ' terminated. Strings in Visual Basic are not null-terminated.
             ' The null character must be removed from the C strings to be used
             ' cleanly in Visual Basic.
             lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) - 1)
          Else

             ' An error occurred.
             MsgBox "Unable to get the name."
             End
          End If

          ' Display the name of the person logged on to the machine.
          MsgBox "The person logged on this machine is: " & lpUserName

       End Sub

     

    Wednesday, May 3, 2006 11:06 AM
  • Application.UserName
    Wednesday, October 28, 2009 5:23 PM
  • Just tried thes suggestons on Windows Server 2008 R2 and it does not work properly.  In stead of user name it gives back the the user is an "Administrator".  Anybody know how to get the logged on User Name from Server 2008 R2?
    Thursday, March 25, 2010 5:54 PM
  • I know this listing is ancient but you rock!
    Friday, September 10, 2010 12:40 PM
  • I know I am responding to an old Post but I am hoping you might have an answer. I tried this on an access project running access 2010 on Windows 7 and I get #Name?. I have tried all inds of VBA code as well to get this to work and this is what I keep getting.
    Tuesday, August 14, 2012 10:23 PM
  • hi,
     
    [code]
    Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
        "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
     
    Sub test()
    MsgBox fOSUserName
    End Sub
     
    Function fOSUserName() As String
    Dim lngLen As Long, lngX As Long
    Dim strUserName As String
        strUserName = String$(254, 0)
        lngLen = 255
        lngX = apiGetUserName(strUserName, lngLen)
        If lngX <> 0 Then
            fOSUserName = Left$(strUserName, lngLen - 1)
        Else
            fOSUserName = ""
        End If
    End Function 'author: cafeine
    [/code]
     
    --
    isabelle
     
    Le 2012-08-14 18:23, Alisida a écrit :
    > I know I am responding to an old Post but I am hoping you might have an answer.
     
    > I tried this on an access project running access 2010 on Windows 7 and I get #Name?.
     
    > I have tried all inds of VBA code as well to get this to work and this is what I keep getting.
     
    Wednesday, August 15, 2012 12:11 AM
  • note that this hasn't to do with the username typed at the entrance of Access,
    when you set up the "user security" (specific to Access Protection)
    in this case, the username given to you by Access CurrentUser()
     
    --
    isabelle
     
    Le 2012-08-14 20:11, isabelleV a écrit :
    > hi,
    > [code]
    > Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
    >      "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    > Sub test()
    > MsgBox fOSUserName
    > End Sub
    > Function fOSUserName() As String
    > Dim lngLen As Long, lngX As Long
    > Dim strUserName As String
    >      strUserName = String$(254, 0)
    >      lngLen = 255
    >      lngX = apiGetUserName(strUserName, lngLen)
    >      If lngX <> 0 Then
    >          fOSUserName = Left$(strUserName, lngLen - 1)
    >      Else
    >          fOSUserName = ""
    >      End If
    > End Function 'author: cafeine
    > [/code]
    > --
    > isabelle
    > Le 2012-08-14 18:23, Alisida a écrit :
    >  > I know I am responding to an old Post but I am hoping you might have an answer.
    >  > I tried this on an access project running access 2010 on Windows 7 and I get #Name?.
    >  > I have tried all inds of VBA code as well to get this to work and this is what I keep getting.
     
    Wednesday, August 15, 2012 12:52 AM
  • To avoid incompatibilities with 64-bit I'd recommend to not use API calls and instead use the Environ() funktion:

    MsgBox Environ("USERNAME")

    HTH
    Henry

    isabelleV wrote:

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

    Wednesday, August 15, 2012 5:54 AM
  • My, there's some complicated answers here!

    The Windows Script Host Object Model has a 'Network' class with functions you need, and you can access it with a single line of code:

      strUName = CreateObject("WScript.Network").UserName 

    This is an example of late binding, which is A Bad Thing; you should actually declare a reference to Windows Script Host Object Model in Tools; References. It'll be listed by name, or can be found by browsing for Wshom.ocx in the System32 folder.

    The 'correct' code, using an early-bound reference, is shown below. You will notice that there is more of it. Note, also, the defensive coding:

    Public Function UserName() As String ' Returns the user's network name On Error Resume Next ' The correct declaration: Dim objNetwork As IWshRuntimeLibrary.WshNetwork Set objNetwork = New IWshRuntimeLibrary.WshNetwork ' Alternative late-binding: bad for performance and stability, ' but useful for simplicity and code portability ' Dim objNetwork As Object ' Set objNetwork = CreateObject("WScript.Network") ' Defensive coding: Scripting Host and Scripting Runtime are ' often mis-registered due to a botched local security policy If objNetwork Is Nothing Then Shell "Regsvr32 -s scrun.dll", vbHide Application.Wait Now + (1# / 3600 / 24) Shell "Regsvr32 -s wshom.ocx", vbHide Application.Wait Now + (1# / 3600 / 24) Set objNetwork = CreateObject("WScript.Network") End If If objNetwork Is Nothing Then Exit Function End If UserName = objNetwork.UserName Set objNetwork = Nothing End Function


    For completeness, here are the corresponding UserDomain and  ComputerName functions: you will need them if you are working in a multinational company supporting users with multiple workstations, because you will need to know 'Where'? and 'Which?'  as whell as whom.

    Public Function UserDomain() As String ' Returns the user's network domain On Error Resume Next ' The correct declaration: Dim objNetwork As IWshRuntimeLibrary.WshNetwork Set objNetwork = New IWshRuntimeLibrary.WshNetwork ' Alternative late-binding: bad for performance and stability, ' but useful for simplicity and code portability ' Dim objNetwork As Object ' Set objNetwork = CreateObject("WScript.Network")

    ' Defensive coding: Scripting Host and Scripting Runtime are ' often mis-registered due to a botched local security policy If objNetwork Is Nothing Then Shell "Regsvr32 -s scrun.dll", vbHide Application.Wait Now + (1# / 3600 / 24) Shell "Regsvr32 -s wshom.ocx", vbHide Application.Wait Now + (1# / 3600 / 24) Set objNetwork = CreateObject("WScript.Network") End If If objNetwork Is Nothing Then Exit Function End If UserDomain = objNetwork.UserDomain Set objNetwork = Nothing End Function Public Function ComputerName() As String ' Returns the host name, as seen by the network: On Error Resume Next ' The correct declaration:

    Dim objNetwork As IWshRuntimeLibrary.WshNetwork Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    ' Alternative late-binding: bad for performance and stability, ' but useful for simplicity and code portability ' Dim objNetwork As Object ' Set objNetwork = CreateObject("WScript.Network") '

    ' Defensive coding: Scripting Host and Scripting Runtime are ' often mis-registered due to a botched local security policy If objNetwork Is Nothing Then Shell "Regsvr32 -s scrun.dll", vbHide Application.Wait Now + (1# / 3600 / 24) Shell "Regsvr32 -s wshom.ocx", vbHide Application.Wait Now + (1# / 3600 / 24) Set objNetwork = CreateObject("WScript.Network") End If If objNetwork Is Nothing Then Exit Function End If ComputerName = objNetwork.ComputerName Set objNetwork = Nothing End Function


    Share and Enjoy: and watch out for unwanted line-breaks inserted by the forum's text-handling.                      

    Friday, August 24, 2012 1:53 PM
  • "Nigel Heffernan" schrieb im Newsbeitrag news:a5cbe0ae-9ae7-4bf6-87d9-8b7af39e0a78@communitybridge.codeplex.com...

    The Windows Script Host Object Model has a 'Network' class with functions you need, and you can access it with a single line of code:

     strUName = CreateObject("WScript.Network").UserName

    This is an example of late binding, which is A Bad Thing; you should
    actually declare a reference to Windows Script Host Object Model in Tools;

    How you come to this IMNSHO completely wrong conviction?

    Late binding is in almost all cases better than early binding. It's only the convenience and laziness of developpers to get intellisense to use early binding and not removing it before deploying the application.
    There are several reasons for this. The most important one is: If an object during runtime can't be bound the application works correctly if it's late bound. If it's bound early the references are completely unresolveable and you will not be able to use the application at all. Even simplest methods in VBA or any other required typelibrary will fails as the chain to resolve the libraries is broken by the brocken reference.
    Another reason is: early binding requires all object models to be loaded during startup of the application, resulting in an unnecessary overhead as you may not need all typelibraries when you run your application.

    Just an example: Early bind Microsoft Office Outlook. Transfer your application to a computer where Outlook isn't installed. It will not work at all. Use late binding for it and an error occurs only if you really do something with Outlook from your application, like sending an e-mail thru Outlook or reading any of it's objects. This error can be tracked easily if you call the GetObject and CreateObject methods.

    My recommendation: If possible always use late binding. Exceptions are the two required typelibraries VBA and Access and the data access library (DAO or ADO, what ever you use) because you will need it always for your data accesses.

    Henry

    Monday, August 27, 2012 7:05 AM
  • Thanks - I needed that!

    Jeff

    Tuesday, July 8, 2014 3:46 PM
  • Clap, clap.
    Wednesday, February 21, 2018 9:21 PM
  • Close, actually Application.UserName

    ;-)

    Thursday, August 9, 2018 7:14 PM