Error Handling Block Always Executes

Schadenfreud

New Member
Joined
Jan 22, 2014
Messages
29
Code:
Private Sub UserForm_Initialize()
Dim myWorksheet As Worksheet


    With lstSheets
        .MultiSelect = fmMultiSelectMulti
        .ListStyle = fmListStyleOption
        For Each myWorksheet In Worksheets
            If myWorksheet.Visible = xlSheetVisible Then
                'add each visible worksheet to the listbox
                .AddItem myWorksheet.Name
            End If
        Next myWorksheet
    End With
End Sub


Private Sub lstSheets_Change()
Dim i As Integer


    For i = 0 To lstSheets.ListCount - 1
        If lstSheets.Selected(i) = True Then
            Worksheets(i + 1).Visible = False 'error occurs on this line
            Else: Worksheets(i + 1).Visible = True
        End If
    Next i
    
'ErrHandler:
    'MsgBox ("There must be at least one visible sheet!")
    'Exit Sub
End Sub

This form shows and hides sheets with the click of a checkbox, but when I'm left with just 1 visible form and I try to hide it, naturally I get an error. I tried handling it with this code, right after the line where the error might occur:
Code:
On Error GoTo ErrHandler:
As a result I got an endless loop (when I was using Resume instead of Exit Sub) of popping message boxes, and no matter what I do, the ErrHandler block always executes at the start of the program, which makes no sense, unless I get an error with the initialization of the form and even then, it shouldn't be like that, because the ErrHandler block is in the _Change() method.

So long story short, I want an error message to pop up when someone tries to hide the last visible sheet, the program should skip the '.Visible = False' line and continue on its merry way.
 
There should be an
Code:
Exit Sub
line before the
Code:
ErrHandler:
line.
 
Upvote 0

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