2015-01-08 99 views
0

嘿有一個簡單的問題我正在編寫一個代碼,隱藏工作表的名單是基於工作表名稱旁邊的字段是或不是。因此,我列出了29張工作表,我希望我的代碼能夠查看該名稱旁邊的字段,並且如果它顯示時顯示它,並且它顯示爲否,它將隱藏它。基於列表隱藏工作表

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
Dim ws As Worksheet 

    For Each ws In Worksheets 
     If ws.Name = Worksheets("Settings").Range("B4:B32") _ 
     And Worksheets("Setting").Range("C4:C32") = "Yes" Then 
      ws.Visible = True 
     End If 
     If ws.Name = Worksheets("Settings").Range("B4:B32") _ 
     And Worksheets("Setting").Range("C4:C32") = "No" Then 
      ws.Visible = True 
     End If 
    Next ws 
End Sub 

我運行這個並不斷得到一個不匹配錯誤我是新來編程,所以我不認爲我打電話的東西正確

+0

的'Worksheet_SelectionChange'事件宏被觸發每次你從一個細胞移動時間在工作表上的另一個工作表上。您不太可能需要或想要這種類型的開銷。建議您在有限的B4:C32範圍內使用「Worksheet_Change」(僅觸發更改的值)。順便說一句,你的兩個條件解析爲可見的工作表。 – Jeeped

回答

0

我相信下面的代碼應該滿足您的需求:

Private Sub Worksheet_Change(ByVal Target As Range) 

    Dim wsSettings As Worksheet 
    Dim wsHideShow As Worksheet 
    Dim rngSheets As Range 
    Dim xlCell As Range 
    Dim sheetName As String 

    Set wsSettings = ThisWorkbook.Worksheets("Settings") 
    Set rngSheets = wsSettings.Range("B4:B32") 

    For Each xlCell In rngSheets 
     sheetName = xlCell.Value 

     If sheetName <> "" Then 

      Set wsHideShow = ThisWorkbook.Worksheets(sheetName) 

      If xlCell.Offset(0, 1).Value = "yes" Then 
       wsHideShow.Visible = False 
      Else 
       wsHideShow.Visible = True 
      End If 
     End If 
    Next xlCell 

End Sub 

而不是循環通過您的工作表,循環通過您的列表,並相應地隱藏/顯示工作表。

+0

謝謝你的工作。你們都很難過 – Kevin

+0

很高興爲你效勞。請點擊相應的複選標記圖標來接受我的答案 – silentsurfer

+0

只要整個工作表上的任何*單元格發生更改,此觸發器都不會觸發嗎?如果控制顯示/隱藏動作的唯一單元格在B4:C32中,那麼該動作不應該限制在這些單元格變化時? – Jeeped

0

作爲在打字慢......但我的建議是:

Private Sub WorkSheet_Change(ByVal Target as range) 

    If (Target.Row >= 4 And Target.Row <= 32 And Target.Column = 2) Then 
     Dim i as Integer 
     For i=0 To 28 Step 1 
     If Range("B" & 2 + i).Value = "YES" Then 
      ThisWorkBook.Worksheets(Range("A" & 2 + i).Value).Visible = True 
     Else 
      ThisWorkBook.Worksheets(Range("A" & 2 + i).Value).Visible = False 
     End If 
     Next i 
    End If 

End Sub 

這是隻有在範圍內的B4值fireing:在紙張上B32改變...

希望這有助於...

0

此代碼在標準模塊中運行。它假定主機是設置而不是設置

它遍歷表以及張:

Sub DisplayOrHideSheets() 
    Dim sh As Worksheet 
    For Each ws In Sheets 
     v = ws.Name 
     For Each r In Worksheets("Settings").Range("B4:B32") 
      If r.Value = v Then 
       If r.Offset(0, 1) = "Yes" Then 
        ws.Visible = True 
       Else 
        ws.Visible = False 
       End If 
      End If 
     Next r 
    Next ws 
End Sub