我在同一个工作簿中有两张工作表。第一张称为“源”,第二张称为“结果”。在“源”上,CJ列中有一个唯一的ID。在“结果”中,我的ID位于H列。“源”的日期位于O列。我正在尝试将数据从“源”加载到字典中。加载行时,我试图检查字典中是否已经存在该行。如果有,我需要比较具有相同ID的日期,并只存储较低的值(最早的日期)。
前任。
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值。在下一行中,检查Dec 10并将其替换为Dec 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项目的内容。
提前感谢!
迈克