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

时间:2014-03-17 17:09:15

标签: excel loops excel-vba autofilter vba

我想通过将循环结构更改为自动过滤器结构来简化以下代码。

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

有一种简单的方法吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

确定,简单:

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)这样它只获取使用范围内的可见单元格