2014-09-22 66 views
0

我想从工作簿中获取2张工作表并比较2个不同列数据的宏。比较2表格数据(宏)

  1. 查找“价格差异” D2一些:D999999并尝试将其匹配到“财经所有” E2:E999999

  2. 如果它们匹配,然后从“财经采取相应的数据全部'!G2:G999999并将其粘贴到'价格差异'对应的行中!U2:U999999。

澄清

我想看看在“价格差异”的单元格的值,列“d”,行“2”,然后再看是否有匹配在“财经全部”列'E'(查看整个列以查找匹配)。

如果有,我想从'Finance All','G'列到'Price Variances',列'U',行'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 

末次
我相信我的问题在 “如果x = y,则x.Offset(0,17)= X”
在于在过去的 '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

你有什么问题?现在的宏是什么?如果你要求人们“修正它”,你不会在这个网站上得到任何帮助,但是在试图发现问题或问题时可以得到一些有用的帮助。 – Maciej 2014-09-22 15:16:01

+0

我的问题是,我有什么不工作,我似乎无法找到解决办法。现在宏已经在上面发布了。 我已经走到我的绳索的末端,让它工作 - 宏运行,但没有数据移动。 – Bcarr91 2014-09-22 15:17:20

+0

该线上x的值是什么,您认为是问题的原因?它是不是被原来在细胞中的相同值所取代?你有没有尝试将x.Offset(0,17)设置为某个静态值?列U被填充任何东西?选择包含什么? – Maciej 2014-09-22 15:24:02

回答

1

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

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

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

请注意,此宏非常慢,因为它正在循环y中的每个单元格,即使它已经找到匹配。如果你想找到的第一个,那么我建议你chaning 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,它会为你做很好此整体功能。

+0

好的 - 我需要定义'x'和'y'吗? - 如果是这样 - 我将如何定义2个工作表之间? – Bcarr91 2014-09-22 16:02:13

+0

只需用上面的语句替换你的If语句,它就可以工作。 – APrough 2014-09-22 17:04:37