2015-10-02 138 views
1

我的工作簿包含多個名爲Detail1,Detail2,Detail3等的工作表。我想根據單元格B15的內容對錶單着色。但是,代碼僅爲Detail1着色,並且不會循環穿過其他工作表。我究竟做錯了什麼?代碼不循環通過工作表

Sub Color_by_cell_value() 
Dim X As String 
Dim ws As Worksheet 
    For Each ws In Worksheets 
     If ws.Name Like "Detail*" Then 
      X = Range("B15").Value 
      Select Case X 
      Case Is = "no" 
       Range("A1:AZ100").Select 
       With Selection.Interior 
        .ThemeColor = xlThemeColorAccent3 
        .TintAndShade = 0.799981688894314 
       End With 
       Range("B15").Select 
       With Selection.Interior 
        .Color = 5296274 
       End With 
      Case Is = "yes" 
       Range("A1:AZ100").Select 
       With Selection.Interior 
        .ThemeColor = xlThemeColorAccent2 
        .TintAndShade = 0.599993896298105 
       End With 
       Range("B15").Select 
       With Selection.Interior 
        .Color = 255 
       End With 
      Case Is = "yes/no" 
       Range("A1:AZ100").Select 
       With Selection.Interior 
        .ThemeColor = xlThemeColorAccent6 
        .TintAndShade = 0.799981688894314 
       End With 
       Range("B15").Select 
       With Selection.Interior 
        .Color = 65535 
       End With 
      End Select 
     End If 
    Next ws 
End Sub 

回答

1

有很多方法可以編輯此代碼並使其更高效,但要回答您的問題。 ws.select將line.If ws.Name Like "Detail*" Then

For Each ws In Worksheets 
    If ws.Name Like "Detail*" Then 
     ws.Select 
     X = Range("B15").Value 
     Select Case X 
+0

我知道這是簡單的我錯過了。非常感謝,它的工作。 – cjgc

0

後可能需要您也可以使用ws.Activate

Sub Color_by_cell_value() 
Dim X As String 
Dim ws As Worksheet 

Application.ScreenUpdating = False 

For Each ws In Worksheets 

    If ws.Name Like "Detail*" Then 

     ws.Activate 
     X = Range("B15").Value 

     Select Case X 
     Case Is = "no" 
      Range("A1:AZ100").Select 
      With Selection.Interior 
       .ThemeColor = xlThemeColorAccent3 
       .TintAndShade = 0.799981688894314 
      End With 
      Range("B15").Select 
      With Selection.Interior 
       .Color = 5296274 
      End With 
     Case Is = "yes" 
      Range("A1:AZ100").Select 
      With Selection.Interior 
       .ThemeColor = xlThemeColorAccent2 
       .TintAndShade = 0.599993896298105 
      End With 
      Range("B15").Select 
      With Selection.Interior 
       .Color = 255 
      End With 
     Case Is = "yes/no" 
      Range("A1:AZ100").Select 
      With Selection.Interior 
       .ThemeColor = xlThemeColorAccent6 
       .TintAndShade = 0.799981688894314 
      End With 
      Range("B15").Select 
      With Selection.Interior 
       .Color = 65535 
      End With 
     End Select 
    End If 
Next ws 

Application.ScreenUpdating = True 

End Sub 

注意我還設置了Application.ScreenUpdatingFalse是一個很好的習慣。

+0

謝謝!是的,我現在停用屏幕更新,它的工作原理! – cjgc