下面的代碼需要有所不同的方法,您的問題。您會注意到,它假設Sheet1在列A中具有一組值,並加上了未指定數量的數據列,並且Sheet2在列A中只有一組值,與Sheet1列A值匹配。
的代碼執行以下操作:
- 在列創建匹配值的最後的數據列的右側在工作表1(1 =不匹配的,0 =匹配)
- 設置一個自動篩選在工作表1數據範圍上,匹配列上的標準值爲1(即,,過濾器只顯示無匹配)
- 分配過濾的行可變
- 的範圍內移除過濾器,並清除的匹配列
- 隱藏在本體的行中變量的範圍內識別
我使用A列中的300,000行代碼值的Sheet1數據集以及B和C列中的隨機數字數據對Sheet1數據集進行了測試,在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
在處理問題上已經有很多帖子了。搜索'vba hide columns' ...看到這個:[SO搜索](http://stackoverflow.com/questions/17461130/vba-searching-through-rows-and-their-associated-columns-and-hide-列,如果有的話) –
@ d-stroyer我已經看到了很多他們,但我的問題是,我的Excel文件非常龐大,我想知道最快的方式。因爲知道我寫了一個宏,而且它運行了30多分鐘......你知道大約需要多少時間來完成我想要的宏嗎?我想可能是我犯了一些錯誤,它會運行無限循環... – Asiat