以下代码对您的问题采取了一些不同的方法。您会注意到,它假定 Sheet1 在 A 列中有一组值加上未指定数量的数据列,并且 Sheet2 在 A 列中只有一组值,Sheet1 列 A 值与之匹配。
该代码执行以下操作:
- 在工作表 1 中最后一个数据列右侧的列中创建匹配值(1 = 不匹配,0 = 匹配)
- 在工作表 1 数据范围上设置自动过滤器,匹配列上的标准值为 1(即过滤器以仅显示不匹配项)
- 将过滤后的行分配给范围变量
- 删除过滤器并清除匹配列
- 批量隐藏范围变量中标识的行
我使用 Sheet1 数据集测试了该过程,该数据集包含 A 列中的 300,000 行代码值以及 B 和 C 列中的随机数字数据,Sheet2 中只有 1,000 多个匹配值。构造随机生成的 10 个字符的代码和匹配值,以便 Sheet1 列 A 值的 20% 不匹配。
针对这些数据的运行时间平均不到两分钟。
Sub MatchFilterAndHide2()
Dim calc As Variant
Dim ws1 As Worksheet, ws2 As Worksheet
Dim ws1Name As String, ws2Name As String
Dim rng1 As Range, rng2 As Range
Dim hideRng As Range
Dim lastRow1 As Long, lastRow2 As Long
Dim lastCol1 As Long
Application.ScreenUpdating = False
calc = Application.Calculation
Application.Calculation = xlCalculationManual
ws1Name = "Sheet1"
Set ws1 = Worksheets(ws1Name)
With ws1
lastRow1 = .Range("A" & .Rows.Count).End(xlUp).Row
lastCol1 = .Cells(1, ws1.Columns.Count).End(xlToLeft).Column + 1
Set rng1 = .Range(.Cells(1, 1), .Cells(lastRow1, lastCol1))
End With
ws2Name = "Sheet2"
Set ws2 = Worksheets(ws2Name)
With ws2
lastRow2 = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng2 = .Range("A2:A" & lastRow2)
End With
'add column of match values one column to the right of last data column
'1 = no-match, 0 = match
With ws1.Range(ws1.Cells(2, lastCol1), ws1.Cells(lastRow1, lastCol1))
.FormulaArray = "=N(ISNA(MATCH(" & ws1Name & "!" & rng1.Address & _
"," & ws2Name & "!" & rng2.Address & ",0)))"
.Value = .Value
End With
'set autofilter on rng1 and filter to show the no-matches
With ws1.Range(ws1.Cells(1, 1), ws1.Cells(1, lastCol1))
.AutoFilter
.AutoFilter field:=lastCol1, Criteria1:=1
End With
With ws1
'assign no-matches to range object
Set hideRng = .Range("A2:A" & lastRow1).SpecialCells(xlCellTypeVisible)
'turn off autofilter, clear match column, and hide no-matches
.AutoFilterMode = False
.Cells(1, lastCol1).EntireColumn.Clear
hideRng.EntireRow.Hidden = True
.Cells(1, 1).Select
End With
Application.Calculation = calc
Application.ScreenUpdating = True
End Sub