【问题标题】:Excel VBA + lookup with DictionaryExcel VBA + 使用字典查找
【发布时间】:2016-07-22 21:27:10
【问题描述】:

我正在尝试使用字典进行查找。但是,我无法提取密钥的offset

我已检查我的 Dict 是否已加载所有我想要的数据,包括必要的 offset 值。 (注释的for next循环)

我现在的问题是,当找到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

【问题讨论】:

  • lookupFound = Dic(profitCentre)

标签: excel dictionary vba


【解决方案1】:

我是通过 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多