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

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.

pjmorris

Well-known Member
Joined
Aug 2, 2012
Messages
1,814
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,099,079
Messages
5,466,492
Members
406,484
Latest member
kaksolver

This Week's Hot Topics

Top