将循环更改为自动过滤以简化MACRO

我想通过改变循环结构到一个自动filter结构来简化下面的代码。

1 ActiveCell.Columns("A:A").EntireColumn.Select If Selection.Find(What:="~* C", After:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=True) Is Nothing Then GoTo 2 End If Selection.Find(What:="~* C", After:=ActiveCell, LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=True).Activate ActiveCell.Select Range(Selection, Selection.Offset(0, 1)).Insert shift:=xlToRight GoTo 1 2 

有没有一个简单的方法来做到这一点?

试试这个:

 Sub test() Dim lastrow As Long Dim rng As Range Dim ar As Range 'change Sheet1 to suit With ThisWorkbook.Worksheets("Sheet1") lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 'find last row in column A .AutoFilterMode = False 'remove previous filter With .Range("A1:A" & lastrow) .AutoFilter Field:=1, Criteria1:="*~* C*" 'apply filter On Error Resume Next Set rng = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) 'find visible rows On Error GoTo 0 End With .AutoFilterMode = False 'remove filter 'if we found some values - insert If Not rng Is Nothing Then rng.Insert Shift:=xlToRight rng.Insert Shift:=xlToRight End If End With End Sub 

如果您的列A不包含标题,请使用rng

 Set rng = .SpecialCells(xlCellTypeVisible) 

顺便说一下,这个职位可能会帮助你在将来: 如何避免使用select/主动语句

确定,方便:

 ActiveCell.Columns("A:A").EntireColumn.Select Selection.AutoFilter 'resets any current autofilter Selection.AutoFilter Field:=1, Criteria1:="=~* C", Operator:=xlFilterValues 

一旦filter应用我通常使用类似于:

 dim rng as range set rng = ActiveSheet.cells.SpecialCells(xlCellTypeVisible) 

让所有可见的单元格(带有活动filter)都只是符合过滤条件的单元格。

编辑

一开始这样做:

 dim numrows as long dim numcolumns as long numrows = Cells.find("*", [A1], , , xlByRows, xlPrevious).Row numcolumns = Cells.find("*", [A1], , , xlByColumns, xlPrevious).Column 

然后过滤之前做这个: set rng = Range("A1", Cells(numrows,numcolumns))

然后在filter之后,而不是使用Activesheet: set rng = rng.cells.SpecialCells(xlCellTypeVisible) ,这样它只能获得使用范围内的可见单元格