Excel VBA自动筛选>删除空行
我们有一张表格用于分析详细的招标stream程,并希望删除任何空行。
每个项目的范围可能不同,最多可能有170列和6000行。
我已经testing的代码正在工作,在一个约。 40列和4750排,只需要10分钟就可以跑了。
寻找任何稍微优雅的解决scheme,以使这一次。 目前的代码将自动筛选每一栏的空白,想知道是否是空的列被过滤是放缓整个事情?
在下面的代码中,我删除了大多数的自动筛选字段以便于查看,但是它从1-175过滤每个字段。
Sub DeleteEmptyRows() With Sheets("Detailed Comparison") Application.DisplayAlerts = False .AutoFilterMode = False Application.ScreenUpdating = False With .Range("F24:FY6000") .AutoFilter .AutoFilter Field:=1, Criteria1:="=" .AutoFilter Field:=2, Criteria1:="=" .AutoFilter Field:=175, Criteria1:="=" End With With .Range("F25:FY6000").SpecialCells(xlCellTypeVisible).Rows.Delete End With Application.DisplayAlerts = True .AutoFilterMode = False Application.ScreenUpdating = True End With End Sub
让事情更优雅
-
当列1-175中的单元格为空时,添加评估为
TRUE
列。 过滤此列。 -
为了更好的定义你需要删除的行,使用一个函数来定义底行(而不是将底行设置为6000。
例如:
Function LastRowInOneColumn(ws As Worksheet, Optional bool As Boolean) As Long 'Find the last used row in a Column 'by default, returns row of column A (FLASE) 'if bool is TRUE then will return row of column B Dim LastRow As Long Dim col As String If bool = True Then col = "B" Else col = "A" End If With ws LastRow = .Cells(.Rows.Count, col).End(xlUp).row End With LastRowInOneColumn = LastRow End Function
速度
我build议您testing一下,看看代码的哪个部分运行的太慢了。 如果是过滤,比build议1(上面)应该有所帮助。 如果是删除,则可能是工作簿的其他部分链接到此数据集,因此在这里删除数据将非常缓慢。 如果是这种情况,我的build议是更改其他数据集,以便它们通过作为DeleteEmptyRowsmacros的第一步删除的命名范围引用此工作表,然后在运行完毕后重新创build这些命名范围macros
Sub set_named_ranges() 'creates named ranges needed for this workbook 'this code is somewhat crude, you may need to modify based on how your data are laid out Dim found As Range Dim col_lookup_text As String dim wks_name As String wks_name = "Detailed Comparison" Worksheets(wks_name).Select Worksheets(wks_name).Range("A1").Select Range(Selection, Selection.End(xlToRight)).Select 'header named range ActiveWorkbook.Names.Add _ Name:=("data_Header"), _ RefersTo:=Range(wks_name & "!" & RngAddress(Selection)) 'main data named range Range(Selection, Selection.End(xlDown)).Select ActiveWorkbook.Names.Add _ Name:=("dataset"), _ RefersTo:=Range(wks_name & "!" & RngAddress(Selection)) End Sub Function RngAddress(rng As Range) As String RngAddress = rng.Address End Function
和:
Sub delete_these_named_ranges(ParamArray names_of_named_ranges() As Variant) 'not a very sexy macro 'feed macro names of named ranges 'deletes the named range 'if named range doesn't exist, it creates a named range with 'that name and deletes it to avoid errors Dim nName As Variant For Each nName In names_of_named_ranges On Error Resume Next ActiveWorkbook.Names.Add Name:=nName, RefersTo:="temp" ActiveWorkbook.Names(nName).Delete Next nName End Sub
您可以添加一个额外的列,其中包含行的所有非空字段的计数 – 例如= COUNTA(F24:FY24) – 然后过滤此列中值为0的行。
我还没有testing过,但猜测应该是更快的方法…