从源代码填充一个字典,得到一个目标数组并用源字典填充它,最后,将结果数组放回目标工作表。
Sub copyData()
Dim i As Long, arr As Variant, dict As Object
Set dict = CreateObject("scripting.dictionary")
dict.comparemode = vbTextCompare
With Worksheets("COMBINED")
'put combined!a:b into a variant array
arr = .Range(.Cells(2, "A"), .Cells(.Rows.Count, "B").End(xlUp)).Value2
'loop through array and build dictionary keys from combined!a:a, dictionary item from combined!b:b
For i = LBound(arr, 1) To UBound(arr, 1)
dict.Item(arr(i, 1)) = arr(i, 2)
Next i
End With
With Worksheets("All SAMs Backlog")
'put 'all sams backlog'!c:d into a variant array
arr = .Range(.Cells(3, "C"), .Cells(.Rows.Count, "C").End(xlUp).Offset(0, 1)).Value2
'loop through array and if c:c matches combined!a:a then put combined!b:b into d:d
For i = LBound(arr, 1) To UBound(arr, 1)
If dict.exists(arr(i, 1)) Then
arr(i, 2) = dict.Item(arr(i, 1))
Else
arr(i, 2) = vbNullString
End If
Next i
'put populated array back into c3 (resized by rows and columns)
.Cells(3, "C").Resize(UBound(arr, 1), UBound(arr, 2)) = arr
End With
MsgBox ("done")
End Sub