Search code examples
vbaexceloutofrangeexception

How to avoid subset out of range when running a delete rows with variable


I know this may have been asked in various formats, however I am completely new to coding and don't understand how to apply it to this function.

I keep getting a subscript out of range error message when running this vba.

Sub KeepOnlyAtSymbolRows()

    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ActiveWorkbook.Sheets("Sheet1")

    lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

    Set rng = ws.Range("A1:A" & lastRow)

    With rng
        .AutoFilter Field:=1, Criteria1:="<>*International SBU*"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With
    ws.AutoFilterMode = False
End Sub

For context my sheet at the moment is 178 rows long and goes up to AK however the number of rows will vary each update the number of columns won't


Solution

  • Be careful when you hard code the name of your sheets like this :

    Set ws = ActiveWorkbook.Sheets("Sheet1")
    

    Because if you change the name in Excel, you'll have to it also in your code (you'll find it out pretty shortly with an error message)

    So different ways to call/reference a sheet :

    Classical, with Sheet's name

    Set ws = ActiveWorkbook.Sheets("Sheet1")
    

    Using index

    Set ws = ActiveWorkbook.Sheets(1)
    

    Using Sheet's object name

    Set ws = ActiveWorkbook.Sheet1
    

    That name won't change, even if you rename the Sheet directly in Excel!

    enter image description here