VBA to return LoginID not user name

LORDMARKS

New Member
Joined
Jun 5, 2014
Messages
39
Morning All

Below is the code I am using to return the full name of the current PC user. I am using this in a selection of workbooks to create user logs, track behavior and speed up data entry. In one project I would like to get the value for the user Login (not name). This is the initial ID used to login to the PC session.

These ID's are in the form of UK12345, when I run my code it returns my full name. Is it possible to return the value for this ID?


Code:
Sub user1()
Dim objInfo
Dim strLDAP
Dim strFullName
  
Set objInfo = CreateObject("ADSystemInfo")
strLDAP = objInfo.UserName
Set objInfo = Nothing
strFullName = GetUserName(strLDAP)
  
'MsgBox "Full name of User is " & strFullName
Sheets("SURVEY1").Range("D8").Value = strFullName
'Sheets("SURVEY2").Range("D8").Value = strFullName
End Sub
Function GetUserName(strLDAP)
  Dim objUser
  Dim strName
  Dim arrLDAP
  Dim intIdx
  
  On Error Resume Next
  strName = ""
  Set objUser = GetObject("LDAP://" & strLDAP)
  If Err.Number = 0 Then
    strName = objUser.Get("givenName") & Chr(32) & objUser.Get("sn")
  End If
  If Err.Number <> 0 Then
    arrLDAP = Split(strLDAP, ",")
    For intIdx = 0 To UBound(arrLDAP)
      If UCase(Left(arrLDAP(intIdx), 3)) = "CN=" Then
        strName = Trim(Mid(arrLDAP(intIdx), 4))
      End If
    Next
  End If
  Set objUser = Nothing
  
  GetUserName = strName
  
End Function

Thanks again all
this is always my first port of call for all things excel?

ps. just getting into MS ACCESS - good support sites?
 

Some videos you may like

Excel Facts

What does custom number format of ;;; mean?
Three semi-colons will hide the value in the cell. Although most people use white font instead.

pjmorris

Well-known Member
Joined
Aug 2, 2012
Messages
1,904
Office Version
2016
Platform
Windows
Try this, although it says username, on my system it returns the Login ID, not my given name:

Code:
Public Function UserName()
    UserName = Environ$("UserName")
End Function
 

Watch MrExcel Video

Forum statistics

Threads
1,102,360
Messages
5,486,388
Members
407,544
Latest member
mguevara

This Week's Hot Topics

Top