I'm trying to make a Excel 2007 vba code to select a sheet using userform. While testing, I'm getting 'Subscript out of range' Error if I input a sheetname which is not there in workbook. my code is below.
Private Sub Okbtn_Click()
sheetname = Me.ComboBox1.Value
If sheetname = "" Then
Unload Me
MsgBox "Sheet Name not enetered", vbExclamation, "Hey!"
Exit Sub
End If
ThisWorkbook.Sheets(sheetname).Activate 'Error points here!!
On Error GoTo errmsg
'If Error.Value = 9 Then GoTo errmsg
Unload Me
MsgBox "Now you are in sheet: " & sheetname & "!", vbInformation, "Sheet Changed"
errmsg:
MsgBox ("Sheet name not found in " & ThisWorkbook.Name & " !")
End Sub
The error is in ThisWorkbook.Sheets(sheetname).Activate
. I tried to put some error handing tricks before and after the problem line, but Im getting the same error-9.
Im very new to coding. I think I explained the problem correctly. I want to avoid the error from popping up, but should show a customized message instead.