A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
On Error is working as designed; the issue is how the error handler is structured.
Key points about On Error in VBA:
-
On Error GoTo labelmust appear before the line that may raise the error, and the label must be a line label inside the same procedure. - When the error occurs, execution jumps to the label. If no error occurs, execution continues normally and will also fall through to the label unless you exit the procedure or branch around it.
-
On Error GoTo 0turns error handling off; it does not “go to line 0”.
In the sample:
On Error GoTo NEXT
Sheets("MyTab").Select
On Error GoTo 0
NEXT:
Problems:
-
NEXTis both a label and a VBA keyword (Nextin loops). Use a different label name (for example,SheetHidden:) to avoid confusion. - If
Sheets("MyTab").Selectfails, control jumps to the label; if it succeeds, execution continues and then falls through into the label code unless explicitly skipped.
A simple pattern to test visibility without relying on Select errors is to check the Visible property directly:
Sub TestSheetVisibility()
Dim ws As Worksheet
On Error GoTo SheetMissing
Set ws = ThisWorkbook.Sheets("MyTab")
On Error GoTo 0 ' sheet exists, turn off handler
If ws.Visible = xlSheetVisible Then
' MyTab is visible
Else
' MyTab is hidden or very hidden
End If
Exit Sub
SheetMissing:
On Error GoTo 0
' Sheet MyTab does not exist
End Sub
If the goal is specifically to branch when Select fails, structure it like this:
Sub TestSelect()
On Error GoTo HiddenOrCannotSelect
Sheets("MyTab").Select
On Error GoTo 0
' Code here runs if MyTab was successfully selected
Exit Sub
HiddenOrCannotSelect:
On Error GoTo 0
' Code here runs if MyTab is hidden, missing, or cannot be selected
End Sub
This uses On Error correctly: handler enabled before the risky line, disabled after, and a distinct label for the error-handling section.
References: