Hide Sheet if Date is Cell is passed

hajiali

Well-known Member
Joined
Sep 8, 2018
Messages
624
Office Version
  1. 2016
Platform
  1. Windows
When the workbook opens I want it hide all sheets if date in Range("P1") is passed. I tried this code however it hides some sheet that the date has not passed and has other sheets visible when date is passed


VBA Code:
Private Sub Workbook_Open()
Dim ws As Worksheet

For Each ws In Worksheets
    If Range("P1") < Now Then
        ws.Visible = xlSheetHidden
    'Else
        'ws.Visible = xlSheetVisible
    End If
Next ws
Set ws = Nothing
End Sub
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
Just looping through worksheets does not actually open or activate them.

So this reference:
VBA Code:
If Range("P1") < Now Then
will be checking the same Range("P1") on the active sheet a whole bunch of times (precisely the number of sheets there are).

You need to qualify the sheet reference, like you did for "ws.Visible..", i.e.
VBA Code:
If ws.Range("P1") < Now Then
 
Upvote 0
Thanks Joe4 If sheets are named "1", "2","3", "4"...etc how would it modify the code to loop through each sheet and compare the dates of each sheet.
 
Upvote 0
Thanks Joe4 If sheets are named "1", "2","3", "4"...etc how would it modify the code to loop through each sheet and compare the dates of each sheet.
You don't need to do any of that.
Just put "ws." in from the Range("P1") like I showed you, and your code should then wotk they way you want.
 
Upvote 0
sorry. I was wondering what the difference was between the two. Totally missed it.
 
Upvote 0

Forum statistics

Threads
1,215,043
Messages
6,122,812
Members
449,095
Latest member
m_smith_solihull

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