vba 使用循环删除工作表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20220661/
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
Deleting worksheets with looping
提问by Tildm
Could you tell me someone why just every second sheet is deleted, however if I turn off the worksheets.delete line than in the message box appears all the sheet names.
你能告诉我为什么只删除第二个工作表,但是如果我关闭 worksheets.delete 行,那么消息框中会出现所有工作表名称。
Sub tor()
Dim wsz As Integer
wsz = Application.Worksheets.Count
For i = 2 To wsz
MsgBox Application.Worksheets(i).Name
Application.DisplayAlerts = False
Application.Worksheets(i).Delete
Next i
End Sub
回答by SBI
What happens is that when you delete a worksheet from the Worksheets collection, the next sheet takes the index of the one you just deleted. You then increment i
, skipping the next sheet that you actually wanted to delete.
发生的情况是,当您从 Worksheets 集合中删除工作表时,下一张工作表将采用您刚刚删除的工作表的索引。然后您增加i
,跳过您实际想要删除的下一张工作表。
The easiest solution is to delete worksheets beginning from the end.
最简单的解决方案是从末尾开始删除工作表。
For i = ThisWorkbook.Worksheets.Count To 2 Step -1
Application.Worksheets(i).Delete
Next i
回答by Siddharth Rout
Delete the sheet in reverse. Every time you delete a sheet, the Sheet index gets shifted.
反向删除工作表。每次删除工作表时,工作表索引都会发生变化。
Sub tor()
Dim wsz As Integer, i as Long
wsz = ThisWorkbook.Worksheets.Count
Application.DisplayAlerts = False
For i = wsz To 2 Step -1
ThisWorkbook.Worksheets(i).Delete
Next i
Application.DisplayAlerts = True
End Sub