删除多个工作表中的内容 - Excel VBA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17141910/
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 content in multiple sheets - Excel VBA
提问by John English
Private Sub CommandButton2_Click()
sheetNo = 1
With Worksheets("Sheet" & sheetNo)
.Range("A1:B12").ClearContents
End With
sheetNo = sheetNo + 1
End Sub
Assume I have 10 sheets (Sheet1, Sheet2, Sheet 3,........) and when I click CommandButton2 it should delete whatever the content in the range A1:B12. But this code deletes the content only in the Sheet1. can someone tell me why and where have I gone wrong?
假设我有 10 张纸(Sheet1、Sheet2、Sheet 3…………),当我单击 CommandButton2 时,它应该删除 A1:B12 范围内的任何内容。但是这段代码只删除了 Sheet1 中的内容。有人能告诉我为什么以及我哪里出错了吗?
Thanks.
谢谢。
回答by
See how to use loops
these are just 3 simple loops examples ( all 3 are doing the same thing ) for you to better understand how loops work
查看如何使用循环
这些只是 3 个简单的循环示例(所有 3 个都在做同样的事情),以便您更好地了解循环的工作原理
Private Sub CommandButton2_Click()
' using for each loop
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
ws.Range("A1:B12").ClearContents
Next
' using for loop with an iterator
Dim i As Long
For i = 1 To Sheets.Count
Sheets(i).Range("A1:B12").ClearContents
Next i
' using do while loop
i = 1
Do While i <= Sheets.Count
Sheets(i).Range("A1:B12").ClearContents
i = i + 1
Loop
End Sub