2016-12-30 100 views
0

我在工作簿中有10個工作表Sample 在總結工作表中,我需要指定一個宏來隱藏和取消隱藏特定工作表,如上面的示例圖所示。隱藏/取消隱藏特定工作表基於按鈕點擊

如果我點擊Button1,則下面列出的所有圖紙Button2都必須隱藏。同樣,如果我點擊Button2,則必須隱藏Button1下列出的所有圖紙。

任何人都可以幫我寫VBA代碼嗎?

我試着用下面的代碼,但它不支持我的2個按鈕:

Sub ShowHideWorksheets() 

    Dim Cell As Range 
    For Each Cell In Range("B6:B7") 

    ActiveWorkbook.Worksheets(Cell.Value).Visible = Not ActiveWorkbook.Worksheets(Cell.Value).Visible 

    Next Cell 

End Sub 

回答

0

試試這個:

Sub ShowHideWorksheets() 

Dim Cell As Range 

For Each Cell In Range("B6:B" & Range("B" & Rows.Count).End(xlUp).row) 
    If Sheets(Cell.Value).Visible = True Then 
     Sheets(Cell.Value).Visible = False 
    Else 
     Sheets(Cell.Value).Visible = True 
    End If 

Next Cell 

End Sub 

你需要作出類似的功能爲第二個按鈕,但具有不同的範圍(可能是在C列)。

+0

您的代碼正在隱藏工作表,如果我再次單擊按鈕它不隱藏工作表 –

+0

好的,請參閱我的編輯。 – Limak

+0

感謝您工作正常,多一個請求,同時單擊按鈕以隱藏其隱藏,但我的光標轉到sheet2。你可以避免這種情況 –

0

在Visual Basic窗口,嘗試打第二個組合框,右上角。

當在工作表中添加一個按鈕時,它應該添加一個「button1.click」函數,如下所示(在法語中:「Bouton1_Cliquer」)。 Combo box picture

然後你只需要複製你的代碼在這個Sub中,併爲第二個按鈕(也可能出現在組合框中)調整它。 它將完成這項工作。

0

建議您在頁面不存在的情況下使用錯誤處理。

Sub Button1() 

Dim rng1 As Range 

On Error Resume Next 

For Each rng1 In Range("B6:B" & Range("B" & Rows.Count).End(xlUp).Row) 
     Sheets(rng1.Value).Visible = False 
Next rng1 
End Sub 


Sub Button2() 

Dim rng1 As Range 

On Error Resume Next 
For Each rng1 In Range("A6:B" & Range("A" & Rows.Count).End(xlUp).Row) 
     Sheets(rng1.Value).Visible = False 
Next rng1 

End Sub