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

我有一个Scripting.Dictionary对象在for循环中填充值对。 问题是,当VLookupfind值并将其打印出来,在debugging好。

 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 

而且我也无法得到这个价值。

在将项目添加到字典时,您已经交换了该值和密钥。 看到这里 。 在你的示例代码中,它应该是:

 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 

让我知道如果这解决了你的问题。