简体   繁体   中英

How to hide Excel Sheet based on cell value using VBA Code

How can I hide various Excel sheets in an Excel document based on a cell's value using a drop down data validation list?

I tried right clicking a sheet and selecting 'view code' and pasting the following code into the pop up Microsoft Visual Basic for Applications window:

Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Blue" Then
Sheets("Sheet3").Visible = False
Else
Sheets("Sheet3").Visible = True
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Yellow" Then
Sheets("Sheet3").Visible = False
Else
Sheets("Sheet3").Visible = True
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Green" Then
Sheets("Sheet3").Visible = False
Else
Sheets("Sheet3").Visible = True
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Purple" Then
Sheets("Sheet3").Visible = False
Else
Sheets("Sheet3").Visible = True
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Fusia" Then
Sheets("Sheet3").Visible = False
Else
Sheets("Sheet3").Visible = True
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Pink" Then
Sheets("Sheet3").Visible = True
Else
Sheets("Sheet3").Visible = False
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Orange" Then
Sheets("Sheet3").Visible = True
Else
Sheets("Sheet3").Visible = False
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Cyan" Then
Sheets("Sheet3").Visible = True
Else
Sheets("Sheet3").Visible = False
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If [G1] = "Gold" Then
Sheets("Sheet3").Visible = True
Else
Sheets("Sheet3").Visible = False
End If
End Sub

I get a pop up message:

The following features cannot be saved in macro-free workbooks: • VB project To save a file with these features, click No, and then choose a macro-enabled file type in the File Type list. To continue saving as a macro-free workbook, click Yes.

The pop up means: You must first save file as "Excel-Macro Enabled" format (*.xlsm)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM