2017-06-08 120 views
1

爲什麼這個宏不會改變我所有工作表的顏色?
它只適用於我的活動工作簿的第一張工作表。
我希望它能通過我工作簿的所有工作表。 感謝名單循環遍歷所有工作表VBA與For Each

Option Explicit 

Private Sub CheckBox13_Click() 
    Dim I As Long, j As Long 
    Dim ws As Worksheet 

    For Each ws In ActiveWorkbook.Worksheets 
     If CheckBox13.Value = True Then 
      For I = 1 To 700 
       For j = 1 To 10 
        If Cells(I, j).Interior.Color = RGB(252, 252, 250) Then 
         Cells(I, j).Interior.Color = RGB(217, 217, 217) 
        End If 
       Next j 
      Next I 
     End If 

     If CheckBox13.Value = False Then 
      For I = 1 To 700 
       For j = 1 To 10 
        If Cells(I, j).Interior.Color = RGB(217, 217, 217) Then 
         Cells(I, j).Interior.Color = RGB(252, 252, 250) 
        End If 
       Next j 
      Next I 
     End If 
    Next 
End Sub 
+3

在所有單元格語句前添加ws。 'ws.Cells(I,j).Interior.Color = ...',除非你指定了你想要的工作表,它將默認爲活動工作表。 – BerticusMaximus

回答

3

當您使用Cells(I, j)是指活動工作表。您會希望在您的參考中使用ws對象,如下所示:

ws.Cells(I, j) 
+1

有關[VBA最佳實踐:永不假設工作表](https://stackoverflow.com/documentation/excel-vba/1107/vba-best-practices/9218/never-assume-the-worksheet)的其他信息。 –