Captain Who
Captain Who

Reputation: 35

Change Loop to Auto Filter

I want to simplify the following code by changing the loop structure to an auto filter structure.

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

Upvotes: 0

Views: 1045

Answers (2)

user1759942
user1759942

Reputation: 1350

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

and once filter is applied I usually use something like:

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

that gets you all of the visible cells, which with a filter active, are only the ones that match the filter criteria.

edit

at the beginning do this:

dim numrows as long
dim numcolumns as long 

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

then before filtering do this: set rng = Range("A1", Cells(numrows,numcolumns))

and then after filter, instead of Activesheet use: set rng = rng.cells.SpecialCells(xlCellTypeVisible) so that way it gets only the visible cells within the used range

Upvotes: 1

Dmitry Pavliv
Dmitry Pavliv

Reputation: 35863

Try this one:

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

If your column A doesn't contain header, use this one for rng:

Set rng = .SpecialCells(xlCellTypeVisible)

Btw, this post may help you in future: How to avoid using Select/Active statements

Upvotes: 1

Related Questions