检查Dict项目是否存在 - 如果是,则比较并保持较低值

时间:2018-01-05 17:29:30

标签: excel vba excel-vba dictionary lookup

我在同一个工作簿中有两张纸。第一张纸称为“Source”,第二张称为“Result”。在“Source”上,我在CJ列中有一个唯一的ID。在“结果”中,我在列H中有我的ID。“源”在列O中有日期。我正在尝试将数据从“源”加载到字典中。当我加载行时,我试图检查它是否已存在于字典中。如果它,我需要比较具有相同ID的日期并仅存储较低的值(最早的日期)。

EX。

Row 1 ID: 123ABC    Date: Dec 10, 2017
Row 2 ID: 123ABC    Date: Dec 15, 2017
Row 3 ID: 123ABC    Date: Dec 5, 2017 

宏应该在2017年12月10日加载123ABC然后在下一行检查并发现123ABC存在并且将12月10日保持为唯一的123ABC值。在下一行,检查和替换12月10日12月5日作为123ABC的唯一值。

字典完成后,我正在进行查找,根据ID检索日期。此查找将使用“结果”中的列H中的ID作为“查找值”,并将日期放入“结果”的列S中。

我到目前为止的代码如下:

Dim x, x2, y, y2()
Dim i As Long
Dim dict As Object
Dim LastRowForDict As Long, LastRowResult As Long, shtSource As Worksheet, shtResult As Worksheet


Set shtSource = Worksheets("Source")
Set shtResult = Worksheets("Result")
Set dict = CreateObject("Scripting.Dictionary")

'load ID and Start dates to dictionary from Source Sheet

With shtSource
    LastRowForDict = .Range("A" & rows.Count).End(xlUp).Row
    x = .Range("CJ2:CJ" & LastRowForDict).Value
    x2 = .Range("O2:O" & LastRowForDict).Value
    For i = 1 To UBound(x, 1)
        dict.Item(x(i, 1)) = x2(i, 1)
        If dict.Exists(x(i, 1)) Then

        'compare two values which shared the same key and replace existing value if new value is smaller

    Next i


End With


'map the values
With shtResult
    LastRowResult = .Range("B" & rows.Count).End(xlUp).Row
    y = .Range("H2:H" & LastRowResult).Value    'looks up to this range
    ReDim y2(1 To UBound(y, 1), 1 To 1)   '<< size the output array
    For i = 1 To UBound(y, 1)
        If dict.Exists(y(i, 1)) Then
            y2(i, 1) = dict(y(i, 1))
        Else
            y2(i, 1) = "0"
        End If
    Next i
    .Range("S2:S" & LastRowResult).Value = y2  '<< place the output on the sheet
End With

我遇到代码比较部分的问题。我认为我使用第If dict.Exists(x(i, 1)) Then行正确开始了。我不确定是否还有其他问题?任何援助将不胜感激。我搜索了但是在比较dict项目方面找不到多少。

提前致谢!

麦克

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情......

For i = 1 To UBound(x, 1)
    If Not dict.exists(x(i, 1)) Then
        dict.Item(x(i, 1)) = x2(i, 1)
    Else
        dict.Item(x(i, 1)) = Application.Min(dict.Item(x(i, 1)), x2(i, 1))
    End If
Next i