使订阅超出范围错误

Posted

技术标签:

【中文标题】使订阅超出范围错误【英文标题】:Getting Subscription out of range Error 【发布时间】:2017-02-25 12:19:48 【问题描述】:

在检查对话框打开的工作簿文件中是否存在“Test_Worksheet”工作表时,代码运行良好。工作簿文件正确打开,如果该文件中存在“Test_Worksheet”表,则 debug.print(在 Sub ChkSalfile 中)给出“Name is True”。

但如果工作簿中的工作表不可用,则会出现“订阅超出范围”错误。请帮忙。我的代码如下

Sub Main()

    Dim salefor As Workbook
    Dim salpathfileName As String, salfileName As String
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        .AllowMultiSelect = False
        .Title = "Please select file."
        .Filters.Clear
        .Filters.Add "Excel 2003", "*.xls?"
        .InitialFileName = "*SAL*.*"

        result4 = .Show

        If (result4 <> 0) Then
            salfileName = Dir(.SelectedItems(1))
            salpathfileName = .SelectedItems(1)
        Else
           'if user pressed CANCEL - exit sub
            Application.ScreenUpdating = True
            MsgBox "User pressed CANCEL"
            Exit Sub
        End If
    End With

    Set salefor = Workbooks.Open(salfileName, ReadOnly:=True)

    Call ChkSalfile(salfileName, salefor)

End Sub


Sub ChkSalfile (salfileName As String, salefor As Workbook)

    Dim chksalsheet As String

    chksalsheet = DoesWorkSheetExist("Test_Worksheet", salfileName)
    If chksalsheet = True Then
        Debug.Print "Name is " & chksalsheet
    Else
        Debug.Print "File not found"
    End If

End Sub


Option Explicit

Public Function DoesWorkSheetExist(WorkSheetName As String, Optional WorkBookName As String)

    Dim WS As Worksheet

    On Error Resume Next
    If WorkBookName = vbNullString Then
        Set WS = Sheets(WorkSheetName)
    Else
        Set WS = Workbooks(WorkBookName).Sheets(WorkSheetName)
    End If
    On Error GoTo 0

    DoesWorkSheetExist = Not WS Is Nothing

End Function

【问题讨论】:

哪一行抛出“订阅超出范围”错误? “Test_worksheet”不存在时出现错误。我认为找不到工作表时未定义çhksalsheet(在chkSalFile子下)变量。 哪一行抛出该错误?单击错误消息框中的“调试”按钮,您将被带到也突出显示的那一行 代码不起作用,由于未定义的 result4 变量,它有编译错误。我试图从中挽救一些东西,但经过 30 分钟的编辑后,我并没有更接近一个合理的问题。 【参考方案1】:

您在 VBA 项目编辑器中的设置似乎设置为在出现任何错误时中断。将此设置更改为仅在未处理的错误时中断:

Tools --> Options --> General Tab --> Error Trapping --> check "Break on Unhadled Errors"

也就是说,当它是 Boolean 时,不要将 Dim 您的变量作为 String

Dim chksalsheet As Boolean ' <-- Not as String

【讨论】:

以上是关于使订阅超出范围错误的主要内容,如果未能解决你的问题,请参考以下文章

JsLint'超出范围'错误

如何使智能指针在exit()时超出范围

贪心算法的汽车加油问题(使列表索引超出范围)

如何使 scipy.interpolate 给出超出输入范围的推断结果?

为啥我没有得到数组超出范围错误? [复制]

Swift 错误:索引超出范围