删除Activesheet后跳过下一个工作表VBA

时间:2019-07-05 10:27:16

标签: excel vba

我正在编写一个宏来验证每张纸上的内容。 如果工作表包含必需的信息,则将其保留,否则将其删除。但是我的问题是,一旦删除工作表,焦点就会自动转到下一个工作表。因此,当代码触及下一页时,它实际上会跳过中间的一页。

我尝试了以下代码:

Sub filterdelete()

Dim current As Workbook
Dim sht As Worksheet
Dim rowN As Integer

Set current = ActiveWorkbook
On Error Resume Next

For Each sht In current.Worksheets
If sht.Name <> "hiddensheet" Then

With sht
    .Select
    .Range("A1").Select
End With

rowN = Cells(Rows.count, 1).End(xlUp).Row

Application.DisplayAlerts = False
If rowN = 1 Then ActiveSheet.Delete
Application.DisplayAlerts = True
End If
Next sht

End Sub

我也尝试过GoTo。但是它正在删除每张纸。 :(

2 个答案:

答案 0 :(得分:2)

在循环中使用一个计数器变量,然后向后移动。

另外,如果您的行数超出了后者的处理能力,请使用Long而不是Integer

Sub filterdelete()

Dim current As Workbook
Dim sht As Worksheet
Dim rowN As Long, i As Long

Set current = ActiveWorkbook

For i = current.Worksheets.Count To 1 step -1
    If current.Sheets(i).Name <> "hiddensheet" Then
        With current.Sheets(i)
            rowN = .Cells(Rows.Count, 1).End(xlUp).Row
            Application.DisplayAlerts = False
            If rowN = 1 Then .Delete
            Application.DisplayAlerts = True
        End With
    End If
Next i

End Sub

答案 1 :(得分:2)

您必须以相反的顺序遍历工作簿中的工作表,以便删除工作表不会导致不良行为。

尝试这样的事情:

For i = current.Worksheets.Count To 1 Step -1
    // your code here
Next i