vba 删除除前 x 份工作表之外的所有工作表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18861809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:23:09  来源:igfitidea点击:

Delete all worksheets except the first x amount of sheets

excelvbaexcel-vba

提问by user2761190

I am trying to delete all worksheets except the first 20 sheets

我正在尝试删除除前 20 张以外的所有工作表

I have this code - Which I thought was working, but I just run it now and it only deletes some of the sheets.

我有这个代码 - 我认为它可以工作,但我现在才运行它,它只删除了一些工作表。

Sub DeleteAll()
    i = Worksheets.Count
    For x = 21 To i
        Application.DisplayAlerts = False
        Worksheets(x).Delete
        Application.DisplayAlerts = True
    Next x
End Sub

回答by mechanical_meat

The sheet indexes change as you delete them. So when you have deleted sheet 21 suddenly you have another sheet 21 which is skipped and sheet 22 is deleted, etc.

当您删除它们时,工作表索引会发生变化。因此,当您突然删除工作表 21 时,您将跳过另一个工作表 21,并删除工作表 22,等等。

One solution is to delete sheets in reverse order beginning with the last sheet. For example:

一种解决方案是从最后一个工作表开始以相反的顺序删除工作表。例如:

Sub DeleteAll()
    i = Worksheets.Count
    For x = i to 21 Step -1 '# <- please note the change here
        Application.DisplayAlerts = False
        Worksheets(x).Delete
        Application.DisplayAlerts = True
    Next x
End Sub

回答by Tim Williams

Do While Worksheets.Count > 20
   Worksheets(21).Delete
Loop