![](/img/trans.png)
[英]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.