Return to Snippet

Revision: 57783
at June 9, 2012 08:29 by joseamirandavelez

Initial Code
Function getLDAPName(clockNumber As String)
    'Declare Variables
    Dim objAdoCon, objAdoCmd, objAdoRS
    Dim objUser, objRootDSE
    Dim strDomainDN, strUserFullName
    Dim intAnswer As Integer
    On Error GoTo Err_NoNetwork
    ' Get current logged in user name
    'strUserFullName = Environ("UserName")
    ' Get the DN of the user's domain
    Set objRootDSE = GetObject("LDAP://rootDSE")
    strDomainDN = objRootDSE.Get("defaultNamingContext")
    ' Search the domain for the user's account object
    Set objAdoCon = CreateObject("ADODB.Connection")
    objAdoCon.Open "Provider=ADsDSOObject;"
    Set objAdoCmd = CreateObject("ADODB.Command")
    Set objAdoCmd.ActiveConnection = objAdoCon
    objAdoCmd.CommandText = _
      "SELECT ADsPath FROM 'LDAP://" & strDomainDN & "' WHERE " & _
      "objectCategory='person' AND objectClass='user' AND " & _
      "sAMAccountName='" & clockNumber & "'"
    Set objAdoRS = objAdoCmd.Execute
    ' If found, get the displayName attribute.
    If (Not objAdoRS.EOF) Then
      Set objUser = GetObject(objAdoRS.Fields("ADsPath").Value)
      'Get common name
      objUser.GetInfoEx Array("CN"), 0
      commonName = objUser.Get("CN")
      'get first name
      objUser.GetInfoEx Array("givenName"), 0
      firstName = objUser.Get("givenName")
      'get last name
      objUser.GetInfoEx Array("SN"), 0
      lastName = objUser.Get("SN")
      'get display name
      objUser.GetInfoEx Array("DisplayName"), 0
      DisplayName = objUser.Get("DisplayName")
      Set objUser = Nothing
      getLDAPName = commonName
      ' handle "not found" error here
     GoTo Err_NoNetwork
    End If
    Set objAdoRS = Nothing
    Set objAdoCmd = Nothing
    Set objAdoCon = Nothing
    Set objRootDSE = Nothing
    Set WshNetwork = Nothing
    GoTo Exit_Sub
        Exit Function
        getLDAPName = "Error"
        GoTo Exit_Sub
End Function

Initial URL

Initial Description
This function is very rough and right now is hard coded to return the common name. This can be useful if, for example, you have a list of usernames in Excel and you want to get the name of the person. However, it can be used in any VBA application.

Initial Title
Get LDAP Full Name from LDAP username

Initial Tags

Initial Language
Visual Basic