vba错误号码9下标超出范围

时间:2015-03-07 08:44:51

标签: excel vba excel-vba error-handling subscript

我尝试制作Excel 2007 vba代码以使用userform选择工作表。在测试时,如果我输入工作簿中没有的工作表名称,我将'下标超出范围' 错误。我的代码如下。

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。

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

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

On Error GoTo errmsg置于ThisWorkbook.Sheets(sheetname).Activate

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

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

答案 2 :(得分:1)

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

    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

答案 3 :(得分:0)

如果工作表存在

,那么错误处理是围绕单行进行测试会更清楚

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

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