我正在尝试编写一个宏,该宏将在工作表1上的A列中查找是否缺少工作表2上的A列或工作表3上的A列中的任何值。如果缺少,则将该值添加到工作表1上A列的底部。相同的值可能存在于工作表2和工作表3上,但它只需要在工作表1上表示一次。
我正在使用下面的代码。
Sub newRow()
Dim rngSh1 As Range, rngSh2 As Range, rngSh3 As Range, mySelSh2 As Range, mySelSh3 As Range
Dim lastRowSh1 As Long, lastRowSh2 As Long, lastRowSh3 As Long
Dim wb As Worksheet
Dim cell As Range
Set wb = ThisWorkbook
With wb
lastRowSh1 = Worksheets("Sheet1").Range("A" & .Rows.Count).End(xlUp).Row
lastRowSh2 = Worksheets("Sheet2").Range("A" & .Rows.Count).End(xlUp).Row
lastRowSh3 = Worksheets("Sheet3").Range("A" & .Rows.Count).End(xlUp).Row
Set rngSh1 = Worksheets("Sheet1").Range("A1:A" & lastRowSh1)
Set rngSh2 = Worksheets("Sheet2").Range("A1:A" & lastRowSh2)
Set rngSh3 = Worksheets("Sheet3").Range("A1:A" & lastRowSh3)
End With
For Each cell In rngSh2.Cells
If IsError(Application.Match(cell.Value, rngSh1, 0)) Then
If mySelSh2 Is Nothing Then
Set mySelSh2 = cell
Else
Set mySelSh2 = Union(mySelSh2, cell)
End If
End If
Next cell
If Not mySelSh2 Is Nothing Then mySelSh2.Copy Destination:=Worksheets("Sheet1").Range("A" & lastRowSh1 + 1)
For Each cell In rngSh3.Cells
If IsError(Application.Match(cell.Value, rngSh1, 0)) Then
If mySelSh3 Is Nothing Then
Set mySelSh3 = cell
Else
Set mySelSh3 = Union(mySelSh3, cell)
End If
End If
Next cell
If Not mySelSh3 Is Nothing Then mySelSh3.Copy Destination:=Worksheets("Sheet1").Range("A" & lastRowSh1 + 1)
End Sub
我已经做了我能想到的每一个调整,但是每一个改变我都会得到一个不同的错误。任何帮助都将不胜感激。谢谢!
1条答案
按热度按时间yuvru6vn1#
使用
Scripting.Dictionary
为您节省一点时间:将非主工作表中的所有值添加到
dict
中,然后遍历该列表;如果在您的主工作表中找不到它,则将然后添加到列表的末尾。值得注意的是,如果用作
dictVal
的Type
值与checkableRange
中评估的数据不相同,则可能导致IsError()
语句始终为True
。