excel - VBA获取用户的名字和姓氏

标签 excel vba

我正在使用以下代码来获取 Windows 用户的名字和姓氏。

用户名在单元格 A2 中,例如:

史密斯博士

该代码有效,但它将用户的姓氏用逗号分隔,然后是他们的名字。 IE:

史密斯,戴夫

我想将其更改为:

Dave.Smith,然后添加 @inbox.com

所以:

Dave.Smith@inbox.com

Sub Test()
    strUser = Range("A2").Value
    struserdn = Get_LDAP_User_Properties("user", "samAccountName", strUser, "displayName")
    If Len(struserdn) <> 0 Then
        MsgBox struserdn
    Else
        MsgBox "No record of " & strUser
    End If
End Sub

Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)

' This is a custom function that connects to the Active Directory, and returns the specific
' Active Directory attribute value, of a specific Object.
' strObjectType: usually "User" or "Computer"
' strSearchField: the field by which to seach the AD by. This acts like an SQL Query's WHERE clause.
'             It filters the results by the value of strObjectToGet
' strObjectToGet: the value by which the results are filtered by, according the strSearchField.
'             For example, if you are searching based on the user account name, strSearchField
'             would be "samAccountName", and strObjectToGet would be that speicific account name,
'             such as "jsmith".  This equates to "WHERE 'samAccountName' = 'jsmith'"
' strCommaDelimProps: the field from the object to actually return.  For example, if you wanted
'             the home folder path, as defined by the AD, for a specific user, this would be
'             "homeDirectory".  If you want to return the ADsPath so that you can bind to that
'             user and get your own parameters from them, then use "ADsPath" as a return string,
'             then bind to the user: Set objUser = GetObject("LDAP://" & strReturnADsPath)

' Now we're checking if the user account passed may have a domain already specified,
' in which case we connect to that domain in AD, instead of the default one.
    If InStr(strObjectToGet, "\") > 0 Then
        arrGroupBits = Split(strObjectToGet, "\")
        strDC = arrGroupBits(0)
        strDNSDomain = strDC & "/" & "DC=" & Replace(Mid(strDC, InStr(strDC, ".") + 1), ".", ",DC=")
        strObjectToGet = arrGroupBits(1)
    Else
        ' Otherwise we just connect to the default domain
        Set objRootDSE = GetObject("LDAP://RootDSE")
        strDNSDomain = objRootDSE.Get("defaultNamingContext")
    End If

    strBase = "<LDAP://" & strDNSDomain & ">"
    ' Setup ADO objects.
    Set adoCommand = CreateObject("ADODB.Command")
    Set ADOConnection = CreateObject("ADODB.Connection")
    ADOConnection.Provider = "ADsDSOObject"
    ADOConnection.Open "Active Directory Provider"
    adoCommand.ActiveConnection = ADOConnection


    ' Filter on user objects.
    'strFilter = "(&(objectCategory=person)(objectClass=user))"
    strFilter = "(&(objectClass=" & strObjectType & ")(" & strSearchField & "=" & strObjectToGet & "))"

    ' Comma delimited list of attribute values to retrieve.
    strAttributes = strCommaDelimProps
    arrProperties = Split(strCommaDelimProps, ",")

    ' Construct the LDAP syntax query.
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
    adoCommand.CommandText = strQuery
    ' Define the maximum records to return
    adoCommand.Properties("Page Size") = 100
    adoCommand.Properties("Timeout") = 30
    adoCommand.Properties("Cache Results") = False

    ' Run the query.
    Set adoRecordset = adoCommand.Execute
    ' Enumerate the resulting recordset.
    strReturnVal = ""
    Do Until adoRecordset.EOF
        ' Retrieve values and display.
        For intCount = LBound(arrProperties) To UBound(arrProperties)
            If strReturnVal = "" Then
                strReturnVal = adoRecordset.Fields(intCount).Value
            Else
                strReturnVal = strReturnVal & vbCrLf & adoRecordset.Fields(intCount).Value
            End If
        Next
        ' Move to the next record in the recordset.
        adoRecordset.MoveNext
    Loop

    ' Clean up.
    adoRecordset.Close
    ADOConnection.Close
    Get_LDAP_User_Properties = strReturnVal

End Function

请问有人可以告诉我我哪里出错了吗?

最佳答案

Please can someone show me where i am going wrong?



您要的是 displayName ,这就是你得到的(“Doe,John”)。您想要的不是“显示名称”,而是用户的名字和姓氏。

让我们看看你在这里得到的函数的签名:
Function Get_LDAP_User_Properties(strObjectType, strSearchField, strObjectToGet, strCommaDelimProps)

最后一个参数名为 strCommaDelimProps ,“字符串,以逗号分隔的属性名称”的缩写。

如果你看看它对 strCommaDelimProps 的作用你给它,你会注意到它被连接到 strQuery它被发送到 LDAP 服务器,然后它也变成了一个名为 arrProperties 的数组。 (天哪,匈牙利命名)​​:
arrProperties = Split(strCommaDelimProps, ",")

然后它遍历查询结果并...
strReturnVal = strReturnVal & vbCrLf & adoRecordset.Fields(intCount).Value

没错,它将每个字段值附加到 strReturnVal字符串,每个结果由 vbCrLf 分隔.

因此,如果您要为函数提供两个用逗号分隔的属性,它将返回一个包含两个值的字符串,由 vbCrLf 分隔。人物。看起来像这样:
"John[CRLF]
Doe"

所以你拿那个字符串,Split它在 vbCrLf制作一个数组,然后 Join它使用点分隔符( . ):
strParts = Get_LDAP_User_Properties("user", "samAccountName", strUser, "givenName,sn")
arrParts = Split(strParts, vbCrLf) 'splits the string into an array
result = Join(arrParts, ".") 'joins array elements back into a string

根据 cyboashu's answer,这两个属性是, "givenName""sn" , 所以你给出函数 "givenName,sn"对于最后一个参数。

那时result字符串看起来像 John.Doe ;在连接 @inbox.com 之前,您可能希望将其设为小写。部分:
result = LCase$(result) & "@inbox.com"
MsgBox result

至于我做错了什么,最新Rubberduck (我的小宠物项目)可以帮助您查明一些事情:

Warning: 'Vbnullstring' preferred to empty string literals - (Book2) VBAProject.Module1, line 69
Warning: 'Vbnullstring' preferred to empty string literals - (Book2) VBAProject.Module1, line 73
Warning: Parameter 'strObjectType' is implicitly Variant - (Book2) VBAProject.Module1, line 11
Warning: Parameter 'strSearchField' is implicitly Variant - (Book2) VBAProject.Module1, line 11
Warning: Parameter 'strObjectToGet' is implicitly Variant - (Book2) VBAProject.Module1, line 11
Warning: Parameter 'strCommaDelimProps' is implicitly Variant - (Book2) VBAProject.Module1, line 11
Warning: Member 'Range' implicitly references ActiveSheet - (Book2) VBAProject.Module1, line 2
Hint: Member 'Test' is implicitly public - (Book2) VBAProject.Module1, line 1
Hint: Member 'Get_LDAP_User_Properties' is implicitly public - (Book2) VBAProject.Module1, line 11
Hint: Parameter 'strObjectType' is implicitly passed by reference - (Book2) VBAProject.Module1, line 11
Hint: Parameter 'strSearchField' is implicitly passed by reference - (Book2) VBAProject.Module1, line 11
Hint: Parameter 'strObjectToGet' is implicitly passed by reference - (Book2) VBAProject.Module1, line 11
Hint: Parameter 'strCommaDelimProps' is implicitly passed by reference - (Book2) VBAProject.Module1, line 11
Hint: Return type of member 'Get_LDAP_User_Properties' is implicitly 'Variant' - (Book2) VBAProject.Module1, line 11
Error: Option Explicit is not specified in 'Module1' - (Book2) VBAProject.Module1, line 1
Error: Local variable 'strUser' is not declared - (Book2) VBAProject.Module1, line 2
Error: Local variable 'struserdn' is not declared - (Book2) VBAProject.Module1, line 3

关于excel - VBA获取用户的名字和姓氏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470891/

相关文章:

vba - 激活名称中包含月份和年份的工作簿

将样式应用于单元格时出现 Excel VBA 粘贴错误

events - 每次我执行某项操作时,Excel 工作表上的列表框中的选择都会变成空白,为什么?

excel - 如何在excel vba中使用 "for each shape in activesheet.shapes"将形状插入指定单元格

vba - 获取对 VBA 事件处理程序中的“表单”复选框的引用

vba - 如果范围中的单元格包含值,则在相邻单元格中插入注释

vba - 在 VBA 中选择文件或文件夹的相同对话框

arrays - 是否可以用符合特定条件的行号填充数组而不循环?

vba - Word VBA - 消除 float 对象表

vba - 将 CSV 合并到一张表中并删除标题