在工作表之间比较和复制数据

时间:2009-11-07 07:42:10

标签: excel vba excel-vba

这就是我想做的事情:

  • 如果
    • 工作表A的单元格H =工作表B的单元格E(包含单词)
    • 工作表A的单元格J =工作表B的单元格H(包含数字)
    • 工作表A的单元格K =工作表B的单元格I(包含数字)
  • ,然后
    • 将工作表A的单元格O复制到工作表B的单元格L(包含数字)

换句话说:

  • 如果工作表A的H2,J2,K2 =工作表B的E1,H1,I1,则将工作表A的O2复制到工作表B的L1。
  • 如果工作表A的H3,J3,K3 =工作表B的E5,H5,I5,则将工作表A的O3复制到工作表B的L5。

我想要的宏应匹配并复制A和B的整个工作表。工作表A中的数据只能使用一次。


到目前为止,这是我所拥有的,但它似乎不起作用。

Dim sh1 As Worksheet, sh2 As Worksheet
Dim j As Long, i As Long, lastrow As Long
Set sh1 = Worksheets("Worksheet A")
Set sh2 = Worksheets("Worksheet B")

lastrow = sh1.Cells(Rows.Count, "A").End(xlUp).Row

For i = 2 To lastrow
   j = (i - 2) * 4 + 1
   If sh1.Cells(i, "H").Value = sh2.Cells(j, "E").Value And _
      sh1.Cells(i, "J").Value = sh2.Cells(j, "H").Value And _
      sh1.Cells(i, "K").Value = sh2.Cells(j, "I").Value Then
      sh1.Cells(i, "O").Copy sh2.Cells(j, "L")
   End If
   j = j + 4
Next

1 个答案:

答案 0 :(得分:2)

更新您需要两个循环来完成您的工作。这个新的子程序适用于任何行。请注意多个匹配,因为它只需要最后一个匹配:

Sub CopyCells()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim j As Long, i As Long, lastrow1 As Long, lastrow2 As Long
    Set sh1 = Worksheets("Worksheet A")
    Set sh2 = Worksheets("Worksheet B")

    lastrow1 = sh1.Cells(Rows.Count, "A").End(xlUp).Row
    lastrow2 = sh2.Cells(Rows.Count, "A").End(xlUp).Row

    For i = 2 To lastrow1
        For j = 1 To lastrow2
            If sh1.Cells(i, "H").Value = sh2.Cells(j, "E").Value And _
                sh1.Cells(i, "J").Value = sh2.Cells(j, "H").Value And _
                sh1.Cells(i, "K").Value = sh2.Cells(j, "I").Value Then
                sh1.Cells(i, "L").Value = sh2.Cells(j, "O").Value
            End If
        Next j
    Next i
End Sub