Excel vba:将vlookup结果添加到字典不起作用

时间:2017-11-07 14:25:54

标签: excel vba excel-vba

我有一个Scripting.Dictionary对象,在for循环中填充值对。问题是,虽然VLookup找到了值并在调试ok中打印出来。

Dim indexes As Object
            Set indexes = CreateObject("Scripting.Dictionary")
            Dim tempYear As Integer
            For tempYear = 2009 To year
    indexes.Add Application.WorksheetFunction.VLookup("TEXT", _
statsWorkbook.Worksheets("economic").Range(rangeString2), tempYear - 1999, 0), tempYear  'here's the adding


            Debug.Print "inside tempYear cycle"
            Debug.Print "vlookup: " & Application.WorksheetFunction.VLookup("TEXT", _
statsWorkbook.Worksheets("economic").Range(rangeString2), tempYear - 1999, 0)   'prints out the right value

            Debug.Print indexes(tempYear)  'doesn't print anything
            Next

编辑:现在我尝试使示例更简单:

Sub testDICT()
    Dim indexes As Object
    Set indexes = CreateObject("Scripting.Dictionary")

    indexes.Add "Lazy boy", "cat"
    indexes.Add "Good boy", "dog"
    indexes.Add "Evil boy", "bear"

    MsgBox (indexes("cat"))
End Sub

我也无法获得价值。

1 个答案:

答案 0 :(得分:0)

您在向字典添加项目时已交换了值和密钥。见here。在您的示例代码中,它应该是:

Sub testDICT()
    Dim indexes As Object
    Set indexes = CreateObject("Scripting.Dictionary")

    indexes.Add "cat", "Lazy boy"
    indexes.Add "dog", "Good boy"
    indexes.Add "bear", "Evil boy"

    MsgBox (indexes("cat"))
End Sub

或者在您的真实代码中:

Dim indexes As Object
            Set indexes = CreateObject("Scripting.Dictionary")
            Dim tempYear As Integer
            For tempYear = 2009 To Year
    indexes.Add tempYear, Application.WorksheetFunction.VLookup("TEXT", _
statsWorkbook.Worksheets("economic").Range(rangeString2), tempYear - 1999, 0)  'here's the adding


            Debug.Print "inside tempYear cycle"
            Debug.Print "vlookup: " & Application.WorksheetFunction.VLookup("TEXT", _
statsWorkbook.Worksheets("economic").Range(rangeString2), tempYear - 1999, 0)   'prints out the right value

            Debug.Print indexes(tempYear)  'doesn't print anything
            Next

如果能解决您的问题,请告诉我。