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

不问归期 提交于 2019-12-24 16:57:59

问题


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


回答1:


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!




回答2:


I assume you are not working with table. If that is the case then try this :

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)
Application.DisplayAlerts = False 'to stop prompting for deletion
With rng
    .AutoFilter Field:=1, Criteria1:="<>*International SBU*"
    .Offset(1, 0).SpecialCells(xlCellTypeVisible).Delete
End With
ws.AutoFilterMode = False
Application.DisplayAlerts = True
End Sub      


来源:https://stackoverflow.com/questions/31287725/how-to-avoid-subset-out-of-range-when-running-a-delete-rows-with-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!