Excel VBA + lookup with Dictionary

2019-09-11 01:20发布

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条回答
Emotional °昔
2楼-- · 2019-09-11 02:13

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
查看更多
登录 后发表回答