我试图清除4到9页上的单元格中的所有内容(包括图像),然后是12和13.我有以下代码,但它清除了表3-9和12-15中的内容不知道为什么。
有什么想法吗?
Sub ClearContents()
Dim i As Integer
For i = 4 To 9 And 12 And 13
Sheets(i).Cells.Clear
Sheets(i).Pictures.Delete
Next i
答案 0 :(得分:2)
尝试以下代码:
Option Explicit
Sub ClearContents()
Dim i As Long
Dim Sht As Worksheet
Dim PicObj As Object
' loop through all worksheets in your workbook
For Each Sht In ThisWorkbook.Sheets
Select Case Sht.Index
Case 4 To 9, 12, 13
Sht.Cells.Clear
' loop through all shapes in your worksheet and delete them all
For Each PicObj In Sht.Shapes
PicObj.Delete
Next PicObj
Case Else '<-- for future cases, if you'll need
'do nothing
End Select
Next Sht
End Sub
答案 1 :(得分:2)
编辑使用工作表名称而不是索引
您可以使用Sheets(array)
集合的Sheets
风格:
Option Explicit
Sub ClearContents()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets(Array("Sheet4", "Sheet5", "Sheet6", "Sheet7", "Sheet8", "Sheet9", "Sheet12", "Sheet13")) ' loop through wanted worksheets
ws.Cells.Clear
ws.Pictures.Delete
Next
End Sub