+ Reply to Thread
Results 1 to 7 of 7

Thread: Deleting Filtered Results in VBA

  1. #1
    Registered User
    Join Date
    06-10-2004
    MS-Off Ver
    Office 2003
    Posts
    70

    Deleting Filtered Results in VBA

    Hello Experts

    I feel I should know how to do this, but I clearly can't. I've tried Google but I'm not sure if I know the question!

    I'm trying to delete certain names from a list, if the name is in the list, the code below works fine. However, if the name doesn't exist Excel deletes all the records!

    I have a number of names that I need to exclude, currently I repeat the filter / delete code for each name. Is there a way of listing the names in an array and using a loop?

    Dim LastRow As Long
        LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
    
        Columns("G:G").Select
        Selection.AutoFilter
    
            Selection.AutoFilter Field:=1, Criteria1:="SMITH*"
            Rows("2:" & LastRow).Select
            Selection.Delete Shift:=xlUp
    
            Selection.AutoFilter Field:=1, Criteria1:="JONES*"
            Rows("2:" & LastRow).Select
            Selection.Delete Shift:=xlUp
    Thanks for your help.

    Colin

    To paraphrase one of your colleagues. I'm self taught and my tutor is an idiot!

  2. #2
    Forum Guru, retired Admin royUK's Avatar
    Join Date
    11-18-2003
    Location
    Derbyshire,UK
    MS-Off Ver
    Xp; 2007; 2010
    Posts
    25,639

    Re: Deleting Filtered Results in VBA

    Try this
    Option Explicit
    
    Sub deleteFiltered()
        Dim rng    As Range
    
        With ActiveSheet
            If Not .AutoFilterMode Then .Range("A1").AutoFilter
            .Range("a1").CurrentRegion.AutoFilter Field:=1, Criteria1:="SMITH*"
    
            With .AutoFilter.Range
                On Error GoTo exithandler
                Set rng = .Offset(1, 0).Resize(.Rows.Count - 1, 1) _
                          .SpecialCells(xlCellTypeVisible)
    
            End With
        End With
        rng.EntireRow.Delete
    exithandler:
    End Sub
    Hope that helps.

    RoyUK
    --------
    If you are pleased with a member's answer then use the Star icon to rate it, if you are pleased enough to part with cash consider a donation to Children in Need

    For Excel Tips & Solutions, free examples and tutorials why not check out my downloads

    New members please read & follow the Forum Rules

    Remember to mark your questions Solved and rate the answer(s)

  3. #3
    Forum Guru
    Join Date
    01-03-2006
    Location
    Taranaki, New Zealand
    MS-Off Ver
    2007 (work & home)
    Posts
    2,242

    Post Re: Deleting Filtered Results in VBA

    hi Colin,

    Give this a whirl...

    Option Explicit
    
    Sub FilterAndDelete()
    Dim LastRow As Long
    Dim ArrOfNames As Variant
    Dim i As Long
    'to speed up the macro
    With Application
        .ScreenUpdating = False
    'with large sheets, calculations at each change of filter can become
    'painfully slow
        .Calculation = xlCalculationManual
    End With
    
    LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
    'define list of names
    ArrOfNames = Array("SMITH*", "JONES*")
    'Loop through names to filter
    For i = LBound(ArrOfNames) To UBound(ArrOfNames)
        Columns("G:G").AutoFilter Field:=1, Criteria1:=ArrOfNames(i)
    'in case no visible cells are found
    On Error Resume Next
            Rows("2:" & LastRow).SpecialCells(xlVisible).Delete Shift:=xlUp
    On Error GoTo 0
    'remove filter
    Columns("G:G").AutoFilter Field:=1
        Next i
    
    'to return settings
    With Application
        .ScreenUpdating = True
        'NB: this assumes your file was originally set on auto-calcuation
        .Calculation = xlCalculationAutomatic
    End With
    End Sub
    hth
    Rob
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

  4. #4
    Forum Guru
    Join Date
    01-03-2006
    Location
    Taranaki, New Zealand
    MS-Off Ver
    2007 (work & home)
    Posts
    2,242

    Re: Deleting Filtered Results in VBA

    LOL :-)

    Roy's is tidier than mine but doesn't do the looping - can you merge all the principles yourself? ;-)
    Give it a go & let us see how it looks...

    I think you will need to change "Field:=1" to be "Field:=7" in Roy's version.

    hth
    Rob
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

  5. #5
    Forum Moderator Richard Buttrey's Avatar
    Join Date
    02-15-2008
    Location
    Grappenhall, UK
    MS-Off Ver
    Excel for Windows & Mac - all versions.
    Posts
    6,566

    Re: Deleting Filtered Results in VBA

    Hi Colin,

    No need for a loop.

    In a separate area on another sheet preferably, add the column G label name, list the names you want to filter underneath this and name this range say "Name_Crit". In this example I'm assuming the column G label header is in G1 and called 'Names'

    Now run the following macro
    Sub FilterNames()
        Range(Range("G1"), Range("G" & Application.Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:=Range("Name_Crit"), Unique:=False
        Range(Range("G2"), Range("G" & Application.Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        ActiveSheet.ShowAllData
    End Sub
    Don't forget that if you run this when you are not on the sheet containing the names, you'll need to modify the macro to include a reference to the sheet name.

    HTH
    Richard Buttrey

    If this was useful then please rate it appropriately.

    Click the small star icon at the bottom left of my post.

  6. #6
    Forum Moderator DonkeyOte's Avatar
    Join Date
    10-22-2008
    Location
    Suffolk, UK
    MS-Off Ver
    2002, 2007 & 2010
    Posts
    21,423

    Re: Deleting Filtered Results in VBA

    To add one more approach to the mix which you can use and avoid having to loop for different names, change sheet etc -- ie process (& delete where appl.) all rows for all names simultaneously:

    Public Sub PurgeNames()
    With Range(Cells(2,"G"),Cells(Rows.Count,"G").End(xlUp)).Offset(,Columns.Count-7)
        .FormulaR1C1 = "=IF(OR(LEFT(RC7,5)=""SMITH"",LEFT(RC7,5)=""JONES""),""x"",1)"
        .SpecialCells(xlCellTypeFormulas,xlTextValues).EntireRow.Delete
        .Clear
    End With
    End Sub
    You can adapt the formula to test for as many different names simultaneously as you want and delete all rows in one go.

    (I've assumed you were deleting the Entire Row - if not the above can be adjusted to delete just cells in G)

  7. #7
    Registered User
    Join Date
    06-10-2004
    MS-Off Ver
    Office 2003
    Posts
    70

    Re: Deleting Filtered Results in VBA

    Hi Guys

    I really don't know how to thank you adequately. Each solution has worked for me, I'll now spend some time adapting them to find the best solution for me.

    It's clear that I need to learn more, especially about error handling.

    Many thanks once again for all of your help.

    Colin

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.2.0