在 VBA Excel 中比较一个工作表中的数据并将其添加到另一个工作表
Compare and Add data from one worksheet to another in VBA Excel
在将现有条目相互比较后,如何将一个工作表中的数据行添加到另一个工作表?
我试过这样做,但唯一的问题是有重复的条目被添加到其中。
For Each Cell1 In Worksheets(1).Range("A1", Worksheets(1).Range("A1").End(xlDown))
For Each Cell3 In Worksheets(3).Range("A1", Worksheets(3).Range("A1").End(xlDown))
If Not Cell1 = Cell3 Then
Dim LastRow3 As Long
LastRow3 = Worksheets(3).Range("A1").SpecialCells(xlCellTypeLastCell).Row + 1
Worksheets(3).Range("A1:C1").Rows(LastRow3).Value = Worksheets(1).Range("A1:C1").Rows(Cell1.Row).Value
Else
Exit For
End If
Next Cell3
Next Cell1
使用 Find() 比使用嵌套循环更易于管理:
Sub Test()
Dim c As Range, f As Range
Dim ws1, ws3
Set ws1 = Worksheets(1)
Set ws3 = Worksheets(3)
For Each c In ws1.Range(ws1.Range("A1"), ws1.Cells(Rows.Count, 1).End(xlUp)).Cells
Set f = ws3.Range(ws3.Range("A1"), _
ws3.Cells(Rows.Count, 1).End(xlUp)).Find( _
What:=c.Value, lookat:=xlWhole)
If f Is Nothing Then
ws3.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(1, 3).Value = _
c.Resize(1, 3).Value
End If
Next c
End Sub
在将现有条目相互比较后,如何将一个工作表中的数据行添加到另一个工作表? 我试过这样做,但唯一的问题是有重复的条目被添加到其中。
For Each Cell1 In Worksheets(1).Range("A1", Worksheets(1).Range("A1").End(xlDown))
For Each Cell3 In Worksheets(3).Range("A1", Worksheets(3).Range("A1").End(xlDown))
If Not Cell1 = Cell3 Then
Dim LastRow3 As Long
LastRow3 = Worksheets(3).Range("A1").SpecialCells(xlCellTypeLastCell).Row + 1
Worksheets(3).Range("A1:C1").Rows(LastRow3).Value = Worksheets(1).Range("A1:C1").Rows(Cell1.Row).Value
Else
Exit For
End If
Next Cell3
Next Cell1
使用 Find() 比使用嵌套循环更易于管理:
Sub Test()
Dim c As Range, f As Range
Dim ws1, ws3
Set ws1 = Worksheets(1)
Set ws3 = Worksheets(3)
For Each c In ws1.Range(ws1.Range("A1"), ws1.Cells(Rows.Count, 1).End(xlUp)).Cells
Set f = ws3.Range(ws3.Range("A1"), _
ws3.Cells(Rows.Count, 1).End(xlUp)).Find( _
What:=c.Value, lookat:=xlWhole)
If f Is Nothing Then
ws3.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(1, 3).Value = _
c.Resize(1, 3).Value
End If
Next c
End Sub