比较两个工作表和复制行数据

时间:2016-10-22 12:51:03

标签: excel excel-vba vba

我想在一个工作簿中比较两个工作表。一些伪代码

  

如果工作表1上的单元格A =工作表2上的单元格A,则如果单元格F打开   工作表1<>工作表2上的单元格F然后从Worksheet2复制行   在工作表1上的行上等等如果工作表1上的单元格A<>细胞A.   在Worksheet2然后左侧将工作表2中的行复制到下一个空白行   工作表1

这是我到目前为止所做的:

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("Sheet1")
Set sh2 = Worksheets("Sheet2")

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, "A").Value = sh2.Cells(j, "A").Value And sh1.Cells(i, "F").Value <> sh2.Cells(j, "F").Value Then
            sh1.Cells(i, "F").Value = sh2.Cells(j, "F").Value
        End If
    Next j
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub CopyCells()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long, counter As Long

    Set sh1 = Worksheets("Sheet1")
    Set sh2 = Worksheets("Sheet2")

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

    For i = 1 To lastrow1
        For j = 1 To lastrow2
            If sh1.Range("A" & i) = sh2.Range("A" & j) And sh1.Range("F" & i) <> sh2.Range("F" & j) Then
                sh2.Range("A" & j).EntireRow.Copy Destination:=sh1.Range("A" & i)
            ElseIf sh1.Range("A" & i) <> sh2.Range("A" & j) Then
                sh2.Range("A" & j).EntireRow.Copy Destination:=sh1.Range("A" & lastrow1 + counter)
                counter = counter + 1
            End If
        Next j
    Next i
End Sub