vba错误号9下标超出范围

vba error number 9 subscript out of range

我正在尝试使用用户表单将 Excel 2007 vba 代码转换为 select sheet。在测试时,如果我输入工作簿中不存在的 sheet 名称,我会收到 'Subscript out of range' 错误。我的代码在下面。

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。我试图在问题行前后放置一些错误处理技巧,但我得到了相同的错误 9。

我对编码很陌生。我想我正确地解释了这个问题。我想避免弹出错误,但应该显示自定义消息。

On Error GoTo errmsg放在ThisWorkbook.Sheets(sheetname).Activate

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

错误处理必须始终在您可以收到错误的行之前

如果您将 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

您需要在执行可能导致错误的指令之前设置错误处理程序。像这样

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

如果工作sheet 存在

,如果您将错误处理围绕单行测试进行,那会更清楚

例如,您当前的代码将标记任何错误 - 例如 sheet 被隐藏 - 因为 sheet 不存在。

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