比较2张数据(宏)

时间:2014-09-22 15:08:34

标签: excel vba excel-vba

我正在尝试获取一个从工作簿中获取2张并比较2个不同数据列的宏。

  1. 在价格差异中找到一个数字'!D2:D999999并尝试将其与“财务全部”匹配!E2:E999999

  2. 如果匹配,则从“财务全部”中获取相应的数据!G2:G999999并将其粘贴到“价格差异”中的相应行中!!U2:U999999

  3. 澄清

    我想在'价格差异'列' D',行' 2'中查看单元格中的值,然后查看&#中是否存在匹配项39;金融全部'专栏' E' (查看整个列以查找匹配项)。

    如果有,我想粘贴来自“财务全部”,“列' G'进入' Price Variances',Column' U',Row' 2' (这是我们搜索匹配的原始单元格的同一行)。

    这需要在“价格差异”列之后处理每一行' 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
    

    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
    

1 个答案:

答案 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,它将为您完成整个功能。