我编写了一些代码,用于完成下一步:
我从这里提示:Excel VBA For Each Worksheet Loop
这是:
Sub ClearAll()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Index <> 1 Then
Call clear(ws)
End If
Next
End Sub
Sub clear(ws As Worksheet)
With ActiveSheet
.Tab.ColorIndex = xlColorIndexNone
.Range(Cells(5, 7), Cells(.Cells(.Rows.Count, "N").End(xlUp).Row - 1, 14)).ClearContents
.Range(Cells(5, 1), Cells(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4)).ClearContents
.Range(Cells(5, 7), Cells(.Cells(.Rows.Count, "N").End(xlUp).Row - 1, 14)).Interior.ColorIndex = 0
.Range(Cells(5, 1), Cells(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4)).Interior.ColorIndex = 0
End With
End Sub
但在运行之后我收到错误运行时错误'1004':应用程序定义或对象定义错误。
我修改了代码。它看起来很可怕:(但至少它有效。
Sub ClearAll1()
Dim quantWs As Integer
Dim a As Integer
quantWs = ActiveWorkbook.Worksheets.Count
a = 2
Do While a <= quantWs
Worksheets(a).Activate
ActiveSheet.Tab.ColorIndex = xlColorIndexNone
Call clear
a = a + 1
Loop
End Sub
Sub clear(ws As Worksheet)
With ActiveSheet
.Tab.ColorIndex = xlColorIndexNone
.Range(Cells(5, 7), Cells(.Cells(.Rows.Count, "N").End(xlUp).Row - 1, 14)).ClearContents
.Range(Cells(5, 1), Cells(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4)).ClearContents
.Range(Cells(5, 7), Cells(.Cells(.Rows.Count, "N").End(xlUp).Row - 1, 14)).Interior.ColorIndex = 0
.Range(Cells(5, 1), Cells(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4)).Interior.ColorIndex = 0
End With
End Sub
有人可以指出第一个样本出了什么问题吗?因为工作版本适得其反......
感谢您的帮助。
答案 0 :(得分:3)
您需要在清除子
中使用ws对象而不是ActiveSheet如果你有一个以上的工作簿,我会将ActiveWorkbook改为ThisWorkbook,打开那些excel将会得到错误的工作簿。如果你为什么会这样,你可以读她:VBA ACTIVEWORKBOOK VS THISWORKBOOK
Sub ClearAll()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Index <> 1 Then
Call clear(ws)
End If
Next
End Sub
Sub clear(ws As Worksheet)
With ws
.Tab.ColorIndex = xlColorIndexNone
.Range(.Cells(5, 7), .Cells(.Cells(.Rows.Count, "N").End(xlUp).Row - 1, 14)).ClearContents
.Range(.Cells(5, 1), .Cells(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4)).ClearContents
.Range(.Cells(5, 7), .Cells(.Cells(.Rows.Count, "N").End(xlUp).Row - 1, 14)).Interior.ColorIndex = 0
.Range(.Cells(5, 1), .Cells(.Cells(.Rows.Count, "D").End(xlUp).Row - 1, 4)).Interior.ColorIndex = 0
End With
End Sub
答案 1 :(得分:2)
您只需将With ActiveSheet
更改为With ws
,但我认为这更容易理解:
Sub clear(ws As Worksheet)
With ws
.Tab.ColorIndex = xlColorIndexNone
With .Range(.Cells(5, 7), .Cells(.Rows.Count, "N").End(xlUp).Offset(-1))
.ClearContents
.Interior.ColorIndex = 0
End With
With .Range("A5", .Range("D" & .Rows.Count).End(xlUp).Offset(-1)))
.ClearContents
.Interior.ColorIndex = 0
End With
End With
End Sub