VBA Retrieve the name of the user associated with logged username

前端 未结 5 1153
渐次进展
渐次进展 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:24

    I've tried so many things, but I suppose my organization does not allow me to query Active Directory (or I got the structure wrong). I could only get my account name (not full name) or the error "No mapping between account names and security IDs was done"

    But after 2 weeks searching, I finally have a working solution that I wanted to share. My final hint can be found here: https://www.mrexcel.com/board/threads/application-username-equivalent-in-ms-access.1143798/page-2#post-5545265

    The value does appear in the registry i.e. "HKEY_CURRENT_USER\Software\Microsoft\Office\Common\UserInfo\UserName"

    Once I realized that, it was easy to access with VBA:

    UserName = CreateObject("wscript.shell").RegRead("HKEY_CURRENT_USER\Software\Microsoft\Office\Common\UserInfo\UserName")
    

    I assume (did not test though) that this is what Application.Username from Excel uses as well. Might not be perfect, but I finally have a solution that works.

提交回复
热议问题