VBA Prevent User from leaving Worksheet (Worksheet_Deactivate)

ExcelKnut

Board Regular
Joined
Apr 18, 2013
Messages
147
I would like to prevent the user from leaving Sheet1 if certain conditions are not met.

I'm using the Worksheet_Deactivate event in the Sheet1 module. However, when the user attempts to leave Sheet1 by selecting Sheet2, the Sheet2 Worksheet_Activate event runs even though I have Application.EnableEvents set to False on the Sheet1 Worksheet_Deactivate event.

I hope that all makes sense. I've been trying to solve this for hours. Any help is GREATLY appreciated!!!

Jeff
 

Excel Facts

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
Keep things simple
A hidden sheet cannot be selected
To keep user on the sheet HIDE all other sheets
Make the sheets visible only when the conditions are met

an example for you (place code in SHEET module)
- here all other sheets are hidden unless both A1 contains a value and A2 contains today's date
- you could also make Worsheet

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    HideSheets
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    HideSheets
End Sub

Private Sub HideSheets()
    Dim ws As Worksheet
    If Range("A1") = "" Or Range("A2") <> Date Then
        For Each ws In ThisWorkbook.Worksheets
            If ws.Name <> Me.Name Then ws.Visible = xlSheetVeryHidden
        Next
    Else
        For Each ws In ThisWorkbook.Worksheets
            ws.Visible = xlSheetVisible
        Next
    End If
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,888
Messages
6,175,213
Members
452,618
Latest member
Tam84

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