通过EXCEL VBA字典循环

时间:2016-06-15 19:15:56

标签: excel vba excel-vba dictionary

我有一个包含以下数据的VBA字典:

ID       NAME       POSITION 
5008004  John Doe   00120096
5008002  John Doe2  00117886
5010010  John Doe3  00117886

我在Excel中记录了以下单元格:

POSITION    SUPERVISOR_NAME
00117886    John Doe
00117886    John Doe2
00117886    John Doe3

当前的Excel VBA代码以下列方式循环遍历字典:

If SUPERVISOR_NAME <> "" Then
    For Each myKey In superDictionary.Keys
            If superDictionary(myKey) = SUPERVISOR_NAME Then
                SUPERVISOR_NAME = myKey
                Exit For
            End If
        Next
End If

无论如何,都会将JOHN DOE名称替换为相关ID。

问题:如何使用相关ID更换JOHN DOE名称但是只有当EXCEL的POSITION和SUPERVISOR_NAME与词典匹配或ELSE提交时才会提交。

2 个答案:

答案 0 :(得分:3)

您似乎没有正确使用Scripting.Dictionary对象的最强大功能之一;这是它快速检索的能力。您实际上想要使用双列条件执行查找,因此请使用两列作为key,将ID作为Item

dictionary_lookup

Option Explicit

Sub supervisorIDs()
    Dim d As Variant, dict As Object
    Dim v As Long, vVALs As Variant

    Set dict = CreateObject("Scripting.Dictionary")
    dict.comparemode = vbTextCompare  'default is vbbinarycompare

    With Worksheets("Sheet4")
        'get values from worksheet
        vVALs = .Range(.Cells(2, 1), .Cells(Rows.Count, 3).End(xlUp)).Value2
        'build dictionary
        For v = LBound(vVALs, 1) To UBound(vVALs, 1)
            'overwrite method - faster (no error control)
            'writes name&position as key, ID as item
            dict.Item(Join(Array(vVALs(v, 2), vVALs(v, 3)), ChrW(8203))) = vVALs(v, 1)
        Next v

        'loop through the second table
        For v = 2 To .Cells(Rows.Count, 6).End(xlUp).Row
            d = Join(Array(.Cells(v, 6).Value2, .Cells(v, 5).Value2), ChrW(8203))
            If dict.exists(d) Then _
                .Cells(v, 7) = dict.Item(d)
        Next v
    End With
End Sub

dictionary_lookup_results

答案 1 :(得分:2)

你的意思是这样吗?

假设您的主管名称在第2行开始的B列中:

Dim r As Long
Dim supervisorName As Range

For Each supervisorName In Range("B2:B" & Cells.(Rows.Count, 2).End(xlUp).Row).Cells
    If superDictionary.Exists(supervisorName.Value) Then
        r = 2 '// First row with data in
        For Each key In superDictionary.Keys
            If superDictionary(key) = supervisorName.Value And supervisorName.Row = r Then
                supervisorName.Value = key
                Exit For
            Else
                r = r + 1
            End If
        Next
    End If
Next