Excel VBA + lookup with Dictionary

扶醉桌前 提交于 2020-01-07 01:16:26

问题


I am trying to do a lookup with dictionary. However, I am not able to extract the offset of the key.

I've checked that my Dict has loaded all of the data that I want, including the necessary offset value. (the for next loop of the commented)

My question now is, how do extract the offset value, when Dic.Exists(profitCentre) is found?

Dim cl As Range, Dic As Object
Set Dic = CreateObject("Scripting.Dictionary"): Dic.Comparemode = vbTextCompare
With Workbooks(wbPropListing).Sheets("Residential")
    For Each cl In .Range("E3:E" & .Cells(Rows.Count, "E").End(xlUp).row)
        If Not Dic.Exists(cl.Value) Then Dic.Add cl.Value, cl.Offset(, 1).Value            
    Next cl
End With
With Workbooks(wbPropListing).Sheets("Fund&CoT")
    For Each cl In .Range("E2:E" & .Cells(Rows.Count, "E").End(xlUp).row)
        If Not Dic.Exists(cl.Value) Then Dic.Add cl.Value, cl.Offset(, 1).Value
    Next cl
End With

'For i = 0 To Dic.Count - 1
'    Debug.Print Dic.items()(i), Dic.keys()(i)
'Next i
i = 0
For Each profitCentre In myProfitCentreArray
    If profitCentre <> "" And Not profitCentre Like "####0000" And Dic.Exists(profitCentre) Then
        lookupFound = Dic.items()
    End If
    Debug.Print "Index: " & i & "   profit centre: " & profitCentre & "   Lookup: " & lookupFound
    i = i + 1
Next profitCentre

回答1:


I found out by doing via vlookup instead of dictionary.

However, if you know the answer via dictionary, I'd like to learn too.

Below is the code that I've done via vlookup

For Each profitCentre In myProfitCentreArray
    If profitCentre <> "" And Not profitCentre Like "####0000" Then
    With Workbooks(wbPropListing).Sheets("Residential")
       Set lookupResRange = .Range("E3:F" & .Cells(Rows.Count, "E").End(xlUp).row)
    End With
    With Workbooks(wbPropListing).Sheets("Fund&CoT")
       Set lookupFundRange = .Range("E2:F" & .Cells(Rows.Count, "E").End(xlUp).row)
    End With

    lookupResult = Application.VLookup(CStr(profitCentre), lookupResRange, 2, False)
    If IsError(lookupResult) Then
       lookupResult = Application.VLookup(CStr(profitCentre), lookupFundRange, 2, False)
       If IsError(lookupResult) Then MsgBox "Profit Centre: " & profitCentre & " Not Found"
       End If
    myforecastSheetsIndex = myforecastSheetsIndex + 1
    End If
Next profitCentre


来源:https://stackoverflow.com/questions/38535490/excel-vba-lookup-with-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!