[英]Compare two EXCEL worksheets and copy similar data onto a third sheet
[英]Compare Two Worksheets and Copy Row Data
我想在一个工作簿中比较两个工作表。 一些伪代码 :
如果工作表1上的单元格A =工作表2上的单元格A
如果工作表1上的单元格F <>工作表2上的单元格F
将工作表2中的行复制到其他工作表1中的行上
如果工作表1上的单元格A>工作表2上的单元格A
将行从Worksheet2复制到Worksheet1上的下一个空白行
这是我到目前为止的内容:
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
结束子
尝试这个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.