vba错误号9下标超出范围

我正在尝试使用ExcelForm来创buildExcel 2007 vba代码来select一个工作表。 在进行testing时,如果input工作簿中不存在的工作表名称,则会出现“下标超出范围”错误。 我的代码在下面。

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 

错误是在ThisWorkbook.Sheets(sheetname).Activate 。 我试图在问题行之前和之后提出一些error handling技巧,但我得到同样的错误-9。

我很新的编码。 我想我正确地解释了这个问题。 我想避免popup的错误,但应该显示一个自定义的消息。

如果将On Error GoTo errmsg代码行移到工作表激活的上方 ,应由错误陷阱例程处理该错误。 如果成功,您只需在到达相同的例程之前退出子。

  On Error GoTo errmsg ThisWorkbook.Sheets(sheetname).Activate 'Error points here!! Unload Me MsgBox "Now you are in sheet: " & sheetname & "!", vbInformation, "Sheet Changed" Exit Sub errmsg: MsgBox ("Sheet name not found in " & ThisWorkbook.Name & " !") End Sub 

在执行可能导致错误的指令之前,您需要设置error handling程序。 像这样的东西

 Private Sub Okbtn_Click() sheetname = Me.ComboBox1.Value If sheetname = "" Then Unload Me MsgBox "Sheet Name not enetered", vbExclamation, "Hey!" Exit Sub End If On Error GoTo errmsg ThisWorkbook.Sheets(sheetname).Activate 'Error points here!! 'If Error.Value = 9 Then GoTo errmsg Unload Me MsgBox "Now you are in sheet: " & sheetname & "!", vbInformation, "Sheet Changed" Exit Sub ' Avoid executing handler code when ther is no error errmsg: MsgBox ("Sheet name not found in " & ThisWorkbook.Name & " !") End Sub 

On Error GoTo errmsg上面ThisWorkbook.Sheets(sheetname).Activate

 ''''' On Error GoTo errmsg ThisWorkbook.Sheets(sheetname).Activate ''''' 

error handling总是必须在可以接收错误的行之前

如果error handling是围绕单行testing,如果工作表存在,则会更清楚

作为一个例子,你当前的代码将标记任何错误 – 比如表单被隐藏 – 表单不存在。

 Private Sub Okbtn_Click() Dim strSht As String Dim ws As Worksheet strSht = Me.ComboBox1.Value If Len(strSht) = 0 Then Unload Me MsgBox "Sheet Name not entered", vbExclamation, "Hey!" Exit Sub End If On Error Resume Next Set ws = ThisWorkbook.Sheets(strSht) On Error GoTo 0 If Not ws Is Nothing Then If ws.Visible Then Application.Goto ws.[a1] MsgBox "Now you are in sheet: " & strSht & "!", vbInformation, "Sheet Changed" Else MsgBox ("Sheet exists but is hidden") End If Else MsgBox ("Sheet name not found in " & ThisWorkbook.Name & " !") End If End Sub