在VBA上下标超出范围
我正在写我的第一个VBA。 我有一个名为Sheet1
的工作表。 该表有一列E
; 我想删除列E
上有一个空字段的所有行。
所以我写了这个代码:
Sub EmptyCells() Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete End Sub
但是,当我运行它,我得到这个错误:
下标超出范围
为什么会发生此错误? 我确定E
列存在于Sheet1
。 我的引用不正确?
编辑
如果我尝试Columns("E")
或Range("E:E")
,而不是Columns("E:E")
我得到相同的错误
如果E列中有任何REAL空单元格( 在UsedRange内 ),则您的代码将工作。
您可能有包含公式的单元格返回Null 。 SpecialCells
不认为它们是空的。 您可能在列E中包含Null的单元格作为常量; SpecialCells
也认为他们填充。
编辑#1:
根据您的具体错误信息确保工作表名称拼写正确 。 Sheet1
与Sheet1
不一样
如果您有名为/标题为Sheet1
的工作表,您的代码将起作用。
Sub EmptyCells() Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete End Sub
请注意,有不同的方式来调用工作表。
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).
我已经试过这个,它的工作原理:
Option Explicit Sub TetsMe() MsgBox (Worksheets(1).Parent.Name & VbCrLf & Worksheets(1).Name) Worksheets(1).Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete End Sub
与索引不同的语法可能会引用不同的工作表。 在这种情况下Worksheets(1)
是工作簿中的第一个工作表。
MsgBox()
会告诉你哪个工作表和你正在改变哪个工作簿。 一旦你知道,你在做什么,你可以删除它。
如果问题出现在工作簿名称中,则很容易将其更改为:
With Workbooks("NameYourWorkbook").Worksheets("NameYourWorksheet") .Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete End With