我正在尝试获取一个从工作簿中获取2张并比较2个不同数据列的宏。
在价格差异中找到一个数字'!D2:D999999并尝试将其与“财务全部”匹配!E2:E999999
如果匹配,则从“财务全部”中获取相应的数据!G2:G999999并将其粘贴到“价格差异”中的相应行中!!U2:U999999
以下是我到目前为止 - 请调整&必要时更正。
Sub Price_Variation_Finance_Match()
Dim CompareRange As Variant, x As Variant, y As Variant
' Set CompareRange equal to the range to which you will
' compare the selection.
Set CompareRange = Range("'Finance All'!E2:E999999")
' NOTE: If the compare range is located on another workbook
' or worksheet, use the following syntax.
' Set CompareRange = Workbooks("Daily Pricing (5)"). _
' Worksheets("Price Variances", "Finance All").Range("E2:E999999")
' Loop through each cell in the selection and compare it to
' each cell in CompareRange.
For Each x In Selection
For Each y In CompareRange
If x = y Then x.Offset(0, 17) = x
Next y
Next x
End Sub
我相信我的问题在于最后一个' x'在"如果x = y那么x.Offset(0,17)= x"
以下是原始宏
Sub Find_Matches()
Dim CompareRange As Variant, x As Variant, y As Variant
' Set CompareRange equal to the range to which you will
' compare the selection.
Set CompareRange = Range("C1:C5")
' NOTE: If the compare range is located on another workbook
' or worksheet, use the following syntax.
' Set CompareRange = Workbooks("Book2"). _
' Worksheets("Sheet2").Range("C1:C5")
'
' Loop through each cell in the selection and compare it to
' each cell in CompareRange.
For Each x In Selection
For Each y In CompareRange
If x = y Then x.Offset(0, 1) = x
Next y
Next x
End Sub
答案 0 :(得分:1)
你的If语句将返回x的原始值。我想相反,你会想要
If x = y Then x.Offset(0, 17) = y.Offset(0, 2)
这为您提供了在查找右侧两列y列中找到的值。
请注意,此宏非常慢,因为它在y中循环遍历每个单元格,即使它已经找到匹配项。如果你想找到第一个,那么我建议将你的For Loop转换为
For Each x In Selection
For Each y In CompareRange
If x = y Then
x.Offset(0, 17) = y.Offset(0, 2)
Exit For
End If
Next y
Next x
或者更好的是,只需使用VLOOKUP,它将为您完成整个功能。