簡體   English   中英

下標超出VBA范圍

[英]Subscript out of range on 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列( 在UsedRange中有任何REAL空單元格,則您的代碼將起作用。

您可能具有包含返回Null的公式的單元格。 SpecialCells不認為它們為空。 您可能在E列中包含以Null為常數的單元格; SpecialCells還認為它們已填充。

編輯#1:

根據您的特定錯誤消息, 確保工作表名稱拼寫正確 Sheet1Sheet 1

我已經嘗試過了,並且有效:

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

如果您有一個名為/標題為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).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM