在VBA宏中使用Dictionary的简单VLOOKUP

时间:2017-07-21 19:16:07

标签: vba excel-vba dictionary vlookup excel

我希望通过VBA宏中的字典进行vlookup。我在互联网上看到了一些例子,但它们大多都是非常具体的,我希望得到更多的帮助,以及#34;裸骨和#34;码。我将使用一个我想要实现的简单示例:

  • 查找值是" Orders"中的单元格B2开始的动态范围内的每个单元格的值。工作表(底行各不相同)

  • 表格数组位于动态范围内,从单元格E2开始并延伸到"报告"工作表(底行各不相同)

  • 列索引编号为8(L列)

  • 范围查找是假的

我目前的代码如下:

Sub DictionaryVLookup()
Dim x, y, z(1 To 10)
Dim i As Long
Dim dict As Object
Dim LastRow As Long

LastRow = Worksheets("Report").Range("B" & Rows.Count).End(xlUp).Row


x = Sheets("Orders").Range("B2:B" & LastRow).Value
y = Sheets("Report").Range("E2:E" & LastRow).Value    'looks up to this range
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(x, 1)
    dict.Item(x(i, 1)) = x(i, 1)
Next i

For i = 1 To UBound(y, 1)
    If dict.exists(y(i, 1)) Then
        z(i) = y(i, 1)
    Else
        z(i) = "NA"
    End If
Next i
Worksheets("Orders").Range("Z2:Z" & LastRow).Value = Application.Transpose(z)    'this is where the values are placed

End Sub

我似乎错过了"查找"部分,目前运行没有错误,简单地放置"找到的值"通过查找,但我不知道如何使返回的值被偏移(在这个例子中想要返回列L)。

我还做了一些"弗兰肯斯坦"使用此代码 - 所以我不确定为什么会这样:

   Dim x, y, z(1 To 10)

(1到10)我想要动态,我猜。

这是我第一次尝试以这种方式使用字典 - 希望通过这个简单的例子获得基本的理解,然后我可以在更复杂的情况下实现它。

我知道还有其他方法可以做我正在描述的内容,但希望专门学习字典。

提前感谢您的任何帮助!

1 个答案:

答案 0 :(得分:1)

这样的事情:

Sub DictionaryVLookup()

    Dim x, x2, y, y2()
    Dim i As Long
    Dim dict As Object
    Dim LastRow As Long, shtOrders As Worksheet, shtReport As Worksheet

    Set shtOrders = Worksheets("Orders")
    Set shtReport = Worksheets("Report")
    Set dict = CreateObject("Scripting.Dictionary")

    'get the lookup dictionary from Report
    With shtReport
        LastRow = .Range("E" & Rows.Count).End(xlUp).Row
        x = .Range("E2:E" & LastRow).Value
        x2 = .Range("L2:L" & LastRow).Value
        For i = 1 To UBound(x, 1)
            dict.Item(x(i, 1)) = x2(i, 1)
        Next i
    End With

    'map the values
    With shtOrders
        LastRow = .Range("B" & Rows.Count).End(xlUp).Row
        y = .Range("B2:B" & LastRow).Value    'looks up to this range
        ReDim y2(1 To UBound(y, 1), 1 To 1)   '<< size the output array
        For i = 1 To UBound(y, 1)
            If dict.exists(y(i, 1)) Then
                y2(i, 1) = dict(y(i, 1))
            Else
                y2(i, 1) = "NA"
            End If
        Next i
        .Range("Z2:Z" & LastRow).Value = y2  '<< place the output on the sheet
    End With

End Sub
相关问题