比较2张数据(macros)

我正在试图从工作簿中获取两张工作表,并比较两个不同的数据列。

  1. 在“价格差异”中find一个数字!D2:D999999并尝试将其与“金融全部”匹配!E2:E999999

  2. 如果它们匹配,则从“Finance All”!G2:G999999中取对应的数据并粘贴到“Price Variances”U2:U999999中相应的行中。

澄清

我想查看“价格差异”,“D”列,“2”行中单元格中的值,然后查看“Finance All”列中是否有匹配项“E”(查看整个列的匹配项)。

如果有的话,我想粘贴从“Finance All”,“G”列到“Price Variances”,列“U”,Row'2'(这是原始的同一行细胞,我们正在寻找一个匹配)。

这需要在'Price Variances','D'列中的每一行处理。

以下是我到目前为止 – 请根据需要调整和更正。

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 

结束小组
我相信我的问题在于“If x = y Then x.Offset(0,17)= x”中的最后一个“x”

以下是原始macros

 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 

你的If语句将返回x的原始值。 相反,我想你会想

 If x = y Then x.Offset(0, 17) = y.Offset(0, 2) 

这给你在查找右侧的y列两列find的值。

请注意,这个macros非常慢,因为它循环遍历y中的每个单元格,即使它已经find匹配。 如果你想find第一个,那么我build议把你的For循环链接到

 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,它将很好地为您完成整个function。