尝试删除VBA中单元格范围的错误

时间:2016-08-26 07:13:51

标签: excel vba excel-vba

我已经创建了一个小代码来从2个单独的工作表和以字母N开头的工作表中删除一系列单元格,但是我的代码总是给我错误或Excel崩溃。使用ClearContents方法的第一行和第二行代码给了我这些错误。

Error from the code execution

我的代码:

'clearing ranges
ThisWorkbook.Worksheets("Sheet1").range("A4", range("AY4").End(xlDown)).ClearContents
ThisWorkbook.Worksheets("Sheet2").range("A3", range("AK3").End(xlDown)).ClearContents

'deleting sheets
For Each sh In ThisWorkbook.Worksheets
    If Left(sh.Name, 1) = "N" Then
        ThisWorkbook.Worksheets(sh.Name).Delete
    End If
Next sh

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

出现错误是因为您不允许删除当前for each循环内的对象。尝试使用for循环,如下所示:

For i = ThisWorkbook.Worksheets.Count to 1 Step -1
  If Left(ThisWorkbook.Worksheets(i).name, 1) = "N" Then
    ThisWorkbook.Worksheets(i).Delete
  End If
Next i

答案 1 :(得分:0)

您的Range定义错误,在内部Range方法调用中,您不访问特定工作表的范围,因此它使用默认工作表的Range。第二个问题:如果删除集合中的某些内容,则应该在集合上向后循环,否则Delete操作会在循环期间引导索引更改。

Dim wsheet1 As Worksheet
Dim wsheet2 As Worksheet

Set wsheet1 = ThisWorkbook.Worksheets("Sheet1")
Set wsheet2 = ThisWorkbook.Worksheets("Sheet2")

wsheet1.Columns("A:AY").ClearContents
wsheet2.Columns("A:AK").ClearContents

For i = ThisWorkbook.Worksheets.Count To 1 Step -1
  If Left(ThisWorkbook.Worksheets(i).Name, 1) = "N" Then
    ThisWorkbook.Worksheets(i).Delete
  End If
Next i

答案 2 :(得分:0)

修改,为ClearContents问题添加一些代码

ClearContents 问题

你写了

  

我想删除A4到AY4右下角的范围

现在,它取决于“AY4的右下角”

如果它是AY列上的最后一个非空值,则使用:

With ThisWorkbook.Worksheets("Sheet001")
    .Range("A4", .Cells(.Rows.Count, "AY").End(xlUp)).ClearContents
End With

您可能需要更多代码来处理“AY”列中第一个非空单元格位于第4行上方的情况

工作表删除

你可能想尝试使用“数组”方法来利用Item集合的Worksheets属性的数组 flavor 并删除一次性表格:< / p>

Option Explicit

Sub ws()
    Dim sh As Worksheet
    Dim shtsToDelete As String

    With ThisWorkbook
        For Each sh In .Worksheets
            If Left(sh.name, 1) = "N" Then shtsToDelete = shtsToDelete & sh.name & "\" '<-_| store sht names in a string delimiting them with an invalid character for sheet names
        Next sh
        If shtsToDelete <> "" Then '<--| if any sheet to be deleted has been found
            Application.DisplayAlerts = False '<--| disable alerts to prevent popping out of msgbox prompting you to confirm sheets deletion
            .Worksheets(Split(Left(shtsToDelete, Len(shtsToDelete) - 1), "\")).Delete '<--| delete list-sheets in one shot
            Application.DisplayAlerts = True '<--| enable alerts back
        End If
    End With
End Sub