2016-07-22 109 views
0

我想用字典做查找。但是,我無法提取密鑰的offsetExcel VBA +查找與詞典

我檢查過我的字典已經加載了我想要的所有數據,包括必要的offset值。 (爲評論的下一個循環)

我現在的問題是,如何找到Dic.Exists(profitCentre)找到offset值?

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 
+0

'lookupFound = DIC(profitCentre)' –

回答

0

我通過vlookup而不是字典找到了。

但是,如果你通過字典知道答案,我也想學習。

下面是我通過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