【问题标题】:Deleting sheet in Excel 365在 Excel 365 中删除工作表
【发布时间】:2019-04-16 08:34:03
【问题描述】:

我有以下 VBA 代码:

Sub abc()
Dim wb As Workbook
Set wb = Workbooks("Book1.xlsx")
wb.Sheets("sheet1").Activate
On Error Resume Next
wb.Sheets("Sheet2").Delete
wb.Sheets("Sheet3").Delete
End Sub

我有 1 个空白 Excel 文件 (Book1.xlsx) 和 2 张纸(sheet1 和 sheet2)。

在 Excel 2013 中它可以工作。

Excel 365 中的相同代码抛出错误消息

运行时错误9:下标超出范围

【问题讨论】:

  • 哪一行实际上导致了错误?
  • 你的工作簿中有Sheet3吗?
  • 我使用了“On Error Resume Next”,因此即使“sheet3”不存在,vba 代码也应该跳过该行,并且在 excel 365 中运行时不应出错。

标签: excel vba excel-2013


【解决方案1】:
Option Explicit

Sub abc()

    Dim wb As Workbook

    Set wb = Workbooks("Frou Frou.xlsx") '<- Check if the workbook has the correct name.

    With wb

        Application.DisplayAlerts = False '<- Remove alerts asking for confirmation of deleting the sheet

            .Sheets("Sheet2").Delete '<- Check if the both sheets appear in the workbook.
            .Sheets("Sheet3").Delete

        Application.DisplayAlerts = True '<- Remove alerts

    End With

End Sub

【讨论】:

    【解决方案2】:
    Sub deleteSelectedSheets()
        Dim wb         As Workbook
        Dim sht        As Worksheet
    
        Set wb = Workbooks("Your.xlsx")
    
        For Each sht In wb.Worksheets
            Select Case sht.name
                Case Is = "Sheet1"  ' You can add as many case as you want
                    sht.Delete
                Case Is = "Sheet2"
                    sht.Delete
                Case Else
                    ' Do nothing
            End Select
        Next sht
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2010-10-15
      • 2014-05-15
      • 1970-01-01
      • 2016-03-17
      相关资源
      最近更新 更多