从Excel宏查询Active Directory不起作用

时间:2019-05-12 17:25:40

标签: excel vba

我正在使用以下代码通过传递用户名来查询活动目录的详细信息。下面是我的源代码。但这既不会引发任何错误,也不会导致结果.EOF确实实现了,并且无法获取任何用户详细信息。任何人都知道它是什么意思(result.EOF = true),以及为什么它不返回结果。

Public Function UserInfo(LoginName As String) As String

Dim conn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim oRoot As IADs
Dim oDomain As IADs
Dim sBase As String
Dim sFilter As String
Dim sDomain As String

Dim sAttribs As String
Dim sDepth As String
Dim sQuery As String
Dim sAns As String

Dim user As IADsUser

On Error GoTo ErrHandler:

Set oRoot = GetObject("LDAP://rootDSE")
sDomain = oRoot.Get("defaultNamingContext")
Set oDomain = GetObject("LDAP://" & sDomain)
sBase = "<" & oDomain.ADsPath & ">"
sFilter = "(&(objectCategory=person)(objectClass=user)(name=" _
  & LoginName & "))"
sAttribs = "adsPath"
sDepth = "subTree"

sQuery = sBase & ";" & sFilter & ";" & sAttribs & ";" & sDepth

conn.Open _
  "Data Source=Active Directory Provider;Provider=ADsDSOObject"

Set rs = conn.Execute(sQuery)

If Not rs.EOF Then
    Set user = GetObject(rs("adsPath"))
    With user

    On Error Resume Next

sAns = "First Name: " & .FirstName & vbCrLf
sAns = sAns & "Last Name " & .LastName & vbCrLf
sAns = sAns & "Employee ID: " & .EmployeeID & vbCrLf
sAns = sAns & "Title: " & .Title & vbCrLf
sAns = sAns & "Division: " & .Division & vbCrLf
sAns = sAns & "Department: " & .Department & vbCrLf
sAns = sAns & "Manager: " & .Manager & vbCrLf

sAns = sAns & "Account Expiration Date: " _
     & .AccountExpirationDate & vbCrLf

sAns = sAns & "Password Expiration Date: " _
  & .PasswordExpirationDate

End With
End If
UserInfo = sAns
ErrHandler:

On Error Resume Next
If Not rs Is Nothing Then
    If rs.State <> 0 Then rs.Close
    Set rs = Nothing
End If

If Not conn Is Nothing Then
    If conn.State <> 0 Then conn.Close
    Set conn = Nothing
End If

Set oRoot = Nothing
Set oDomain = Nothing
End Function

0 个答案:

没有答案