2014-09-22 65 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