Public Sub LookupUser()
Dim cn As String
cn = InputBox("Enter the common name", "AD Lookup")
MsgBox GetAdsProp("cn", cn, "mail"), vbOKOnly + vbInformation, "Email"
End Sub
Function GetAdsProp(ByVal SearchField As String, ByVal SearchString As String, ByVal ReturnField As String) As String
' get domain
Dim oRoot
Set oRoot = GetObject("LDAP://RootDSE")
Dim sDomain
sDomain = oRoot.Get("defaultNamingContext")
Dim strLDAP
strLDAP = "LDAP://" & sDomain
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 10000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
' Search the AD recursively, starting at root of the domain
objCommand.CommandText = "SELECT " & ReturnField & " FROM '" & strLDAP & "' WHERE objectCategory='person'AND objectClass='user' and " & SearchField & "='" & SearchString & "'"
' RecordSet
Dim objRecordSet As Object
Set objRecordSet = objCommand.Execute
If objRecordSet.RecordCount = 0 Then
GetAdsProp = "not found" ' no records returned
Else
GetAdsProp = objRecordSet.Fields(ReturnField) ' return value
End If
' Close connection
objConnection.Close
' Cleanup
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objCommand = Nothing
End Function