Excel VBA宏:如何删除除一张纸之外的所有纸?

时间:2018-07-14 09:36:50

标签: excel vba excel-vba

具体来说,我想删除除工作表的代号Sheet6以外的所有工作表,但是我似乎无法使我的代码正常工作。

  Dim ws As Worksheet

  For Each ws In ThisWorkbook.Worksheets
  If ws <> ThisWorkbook.Sheet6 Then

      Application.DisplayAlerts = False
      ws.Delete
      Application.DisplayAlerts = True

  End If

  Next ws

3 个答案:

答案 0 :(得分:3)

尝试

Dim ws As Worksheet

Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
    If ws.CodeName <> "Sheet6" Then ws.Delete
Next
Application.DisplayAlerts = True

答案 1 :(得分:0)

这里是没有变种的候补。

application.displayalerts = false

with ThisWorkbook
    if .worksheets("sheet6").index > 1 then _
        .worksheets("sheet6").move before:=.sheets(1)
    do while .sheets.count > 1
        .sheets(2).delete
    loop
end with

application.displayalerts = true

答案 2 :(得分:0)

删除时,请始终向后迭代(尽管Jeeped的答案有不同的解决方法)。

    Dim iterator as long
    Application.DisplayAlerts = False
    For iterator = ThisWorkbook.Worksheets.Count To 1 Step -1
        With ThisWorkbook.Worksheets(iterator)
            if .CodeName <> "Sheet6" Then .Delete
        End With
    Next iterator
    Application.DisplayAlerts = True