VBA Retrieve the name of the user associated with logged username

前端 未结 5 1152
渐次进展
渐次进展 2020-12-06 06:40

I want to get the full name of the user (logged in already) in VBA. This code I found online would do getting the username:

UserName = Environ(\"USERNAME\")          


        
5条回答
  •  庸人自扰
    2020-12-06 07:10

    Even if this thread is rather old, other users might be still googling around (like me). I found an excellent short solution that worked for me out-of-the-box (thanks to Mr.Excel.com). I changed it because I needed it to return a string with the user's full name. The original post is here.

    EDIT: Well, I fixed a mistake, "End Sub" instead of "End Function" and added a variable declaration statement, just in case. I tested it in Excel 2010 and 2013 versions. Worked fine on my home pc too (no domain, just in a workgroup).

    ' This function returns the full name of the currently logged-in user
    Function GetUserFullName() as String
        Dim WSHnet, UserName, UserDomain, objUser
        Set WSHnet = CreateObject("WScript.Network")
        UserName = WSHnet.UserName
        UserDomain = WSHnet.UserDomain
        Set objUser = GetObject("WinNT://" & UserDomain & "/" & UserName & ",user")
        GetUserFullName = objUser.FullName
    End Function
    

提交回复
热议问题