VBA code needed to hide worksheet based on cell value

MAS59

New Member
Joined
Mar 7, 2021
Messages
2
Office Version
  1. 2016
Platform
  1. Windows
I am new to VBA at the age of 62 and I am trying to teach myself VBA. I have a project that I am working on. The file has a single "interface" worksheet and the other 40 worksheets will have either a "Yes" or a "No" in cell A2. If A2 = "No" I want to hide the worksheet. I currently have code that loops through each worksheet to change the worksheet name based on the value in A1.

VBA Code:
Sub RenameSheets()

For i = 1 To Sheets.Count
  
    Sheets(i).Activate
    ActiveSheet.Name = ActiveSheet.Range("a1").Value
   
Next i
      
Sheets(2).Activate

End Sub

What do I need to add?
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
You can do rename and hide in a single loop. Note the way to loop every sheet in workbook.
Most of the time you do not need to activate the sheet or range to copy if it is defined/declared.. In this case during loop the ws is already the selected sheet (or defined sheet).

VBA Code:
Sub RenameHide()

Dim ws As Worksheet

For Each ws In Sheets
    ws.Name = ws.Range("A1")
    If ws.Range("A2") = "No" Then
        ws.Visible = xlSheetHidden
    End If
Next

End Sub

In you code, you can just write it as
VBA Code:
For i = 1 To Sheets.Count
    Sheets(i).Name = ActiveSheet.Range("a1").Value
Next i
 
Upvote 0
Solution
Perfection! Thanks for the code and the quick response. Also the teaching moment. Old dog and new tricks! I love it.
 
Upvote 0

Forum statistics

Threads
1,214,642
Messages
6,120,698
Members
448,979
Latest member
DET4492

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top