我有一个 Excel 工作簿,其中有一个主工作表来跟踪项目及其当前位置,另一个工作表跟踪过去位置或项目所在的位置。目前,当主表中的记录发生更改时,该行被手动复制并粘贴到第二张表中。我想创建一个宏来查找主表中不在第二张表中的项目,并在记录更改时将它们复制到第二张表中。
下面是我找到并修改的一个示例宏,它很接近,但它复制和粘贴所有行而不是新行或不同行。这些行只需要在 A、B 和 D 列上进行比较。
Public Sub Sample()
Dim shM As Worksheet, sh2 As Worksheet
Dim shMData As Variant
Dim sh2DataA As Variant
Dim sh2Data As Variant
Dim iM As Long, os2 As Long, i2 As Variant
Dim DoSearch As Boolean
Set shM = Sheets(1)
Set sh2 = Sheets(2)
With shM
shMData = .Range(.[A1], .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 4)
End With
DoSearch = False
For iM = 2 To UBound(shMData, 1)
With sh2
sh2DataA = .Range(.[A1], .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 1)
sh2Data = .Range(.[A1], .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 4)
End With
os2 = 0
Do
If UBound(shMData, 1) > 1 Then
i2 = Application.Match(shMData(iM, 1), sh2DataA, 0)
Else
If shMData(iM, 1) = sh2DataA Then
i2 = 1
Else
i2 = CVErr(xlErrNA)
End If
End If
If Not IsError(i2) Then
If (shMData(iM, 2) = sh2Data(i2, 2)) And (shMData(iM, 4) = sh2Data(i2, 4)) Then
MsgBox "Match found Master = " & iM & ", sheet2 = " & i2 + os2
Else
shM.Activate
shM.Range(Cells(iM, 1), Cells(iM, 7)).Select
Selection.Copy
sh2.Select
FinalRow = Range("A65536").End(xlUp).Row
NextRow = Range("A65536").End(xlUp).Row + 1
Range("A" & NextRow).Select
ActiveSheet.Paste
End If
os2 = os2 + i2
If os2 < UBound(sh2Data, 1) Then
With sh2
sh2DataA = .Range(.Cells(i2 + os2, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 1)
sh2Data = .Range(.Cells(i2 + os2, 1), .Cells(.Rows.Count, 1).End(xlUp)).Resize(, 4)
End With
DoSearch = True
Else
DoSearch = False
End If
Else
shM.Activate
shM.Range(Cells(iM, 1), Cells(iM, 7)).Select
Selection.Copy
sh2.Select
FinalRow = Range("A65536").End(xlUp).Row
NextRow = Range("A65536").End(xlUp).Row + 1
Range("A" & NextRow).Select
ActiveSheet.Paste
DoSearch = False
End If
Loop Until Not DoSearch
Next
End Sub
添加消息框只是为了验证代码是否正常工作 - 它不是必需的组件。再次感谢您提供的任何建议。