我已经创建了下面的代码并将其应用到一张纸上并且效果很好,现在我在同一工作簿中创建了多张工作表,并且希望在单击按钮时在第一张纸上运行相同的代码在第一页。所以我创建了下面的代码,但是当我单击Sheet1中的botton时,它在其他工作表上不起作用。
Private Sub CommandButton1_Click()
On Error Resume Next
Dim cng As Range, rng As Range
Application.EnableEvents = False
Dim WS_Count As Integer
Dim I As Integer
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 To WS_Count
Set rng = Range("C14:AG14")
For Each cng In rng
If Cells(14, cng.Column) = "HO" Or Cells(14, cng.Column) = "ho" Or Cells(14, cng.Column) = "Ho" Then
Cells(15, cng.Column) = 8
Cells(14, cng.Column) = ""
Else
Cells(20, cng.Column) = ""
End If
Next cng
Next I
Application.EnableEvents = True
End Sub
答案 0 :(得分:1)
如上所述,删除On错误行不需要它,并且您希望错误在大多数情况下让您知道代码错误的位置。
此外,您需要在工作表中迭代时将工作表设置为范围,否则excel将使用活动工作表:
Private Sub CommandButton1_Click()
Application.EnableEvents = False
Dim cng As Range, rng As Range
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
With WS
Set rng = .Range("C14:AG14")
For Each cng In rng
If .Cells(14, cng.Column) = "HO" Or .Cells(14, cng.Column) = "ho" Or .Cells(14, cng.Column) = "Ho" Then
.Cells(15, cng.Column) = 8
.Cells(14, cng.Column) = ""
Else
.Cells(20, cng.Column) = ""
End If
Next cng
End With
Next WS
Application.EnableEvents = True
End Sub