我想通过将循环结构更改为自动过滤器结构来简化以下代码。
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)
顺便说一句,这篇文章将来可能对您有帮助:How to avoid using Select/Active statements
ActiveCell.Columns("A:A").EntireColumn.Select
Selection.AutoFilter 'resets any current autofilter
Selection.AutoFilter Field:=1, Criteria1:="=~* C", Operator:=xlFilterValues
并且一旦应用了过滤器,我通常会使用类似的东西:
dim rng as range
set rng = ActiveSheet.cells.SpecialCells(xlCellTypeVisible)
这将使您所有可见的单元格处于活动状态,而这些单元格都处于激活状态,只是那些符合过滤条件的单元格。
一开始就是这样做:
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))
然后过滤,而不是使用Activesheet:set rng = rng.cells.SpecialCells(xlCellTypeVisible)
,这样它仅获取使用范围内的可见单元格