简体   繁体   中英

Subscript out of range on VBA

I am writing my first VBA. I have a sheet named Sheet1 . That sheet has a column E ; I would like to delete all rows which have an empty field on column E .

Therefore, I wrote this code:

Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1 . Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E") , instead of Columns("E:E") I get the same error

Your code will work if there are any REAL empty cells in column E ( within UsedRange ).

You may have cells that contain formulas returning Null . SpecialCells does not consider them empty. You may have cells in column E containing Null as a constant; SpecialCells also considers them filled.

EDIT#1:

Based upon your specific error message make sure the worksheet name is spelled correctly . Sheet1 is not the same as Sheet 1

I have tried this and it works:

Option Explicit
Sub TetsMe()
    MsgBox (Worksheets(1).Parent.Name & VbCrLf & Worksheets(1).Name)
    Worksheets(1).Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

The different syntax as the index may refer to a different sheet. In this case Worksheets(1) is the first worksheet in the workbook.

The MsgBox() will tell you which worksheet and which workbook you are changing. Once you know, what you are doing, you may remove it.

If the problem is in the workbook name, then it is easy to change it like this:

With Workbooks("NameYourWorkbook").Worksheets("NameYourWorksheet")
    .Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End With

Your code works if you have a sheet named/titled Sheet1 .

Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

Note that there are different ways to call a sheet.

Sheets("Sheet1") 'means the visible name of the sheet is `Sheet1` (not the same as VBA name)
                 'the number doesn't tell anything about it's position, it's just a name.

Sheet1           'means the VBA name of the sheet.
                 'the number doesn't tell anything about it's position, it's just a name.

Worksheets(1)    'means the first worksheet (which ever is in the first position)

Sheets(1)        'means the first sheet (can also be a chart not only a worksheet)
                 'this has no relation to its name which could be "Sheet5"
                 '(If "Sheet5" is in first position).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM