【问题标题】:"Subscript out of range" error when calling LBound() or UBound() on a VBA array在 VBA 数组上调用 LBound() 或 UBound() 时出现“下标超出范围”错误
【发布时间】:2014-02-07 14:36:15
【问题描述】:

以下代码产生错误“下标超出范围”,我不知道为什么。谁能解释一下?

    Dim errorc As Integer
    Dim myarray() As Variant


    errorc = 1

    If Len(Me.txt_Listnum) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Numer Listy"
    errorc = errorc + 1
    End If

    If Len(Me.cbo_ByWho) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Wystawione przez"
    errorc = errorc + 1
    End If

    If Len(Me.cbo_ForWho) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Wystawione na"
    errorc = errorc + 1
    End If

    For i = LBound(myarray) To UBound(myarray)
        msg = msg & myarray(i) & vbNewLine
    Next i

    If errorc > 0 Then
       MsgBox "da" & msg

    End If

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

    如果填充了所有表单控件,您的代码将失败,因此myarray 永远不会得到ReDim'd。对于未初始化的动态数组,

    Dim myarray() As Variant
    

    (即,随后没有使用ReDim 调整大小的那个),对其调用LBound()UBound() 将失败并显示“下标超出范围”。

    【讨论】:

    • @user3002600 将For 循环放在If errorc ... 块内并检查errorc > 1,而不是0
    【解决方案2】:

    我的 VB(A) 很远,但还在。 (Re)Dim() 方法定义了数组的大小;数组的索引从 0 变为 size-1。因此,当您这样做时:

    errorc = 1
    
    If Len(Me.txt_Listnum) = 0 Then
    ReDim Preserve myarray(errorc)
    myarray(errorc) = "Numer Listy"
    errorc = errorc + 1
    End If
    
    1. 您将 myarray 重新设置为包含 1 个元素 (ReDim Preserve myarray(errorc))。它只有 1 个索引:0
    2. 您尝试在索引 1 (myarray(errorc) = "Numer Listy") 中放置一些内容,这将失败并显示您提到的错误消息。

    所以你应该组织这样的事情:

    errorc = 0
    
    If Len(Me.txt_Listnum) = 0 Then
        errorc = errorc + 1 'if we get here, there's 1 error more
        ReDim Preserve myarray(errorc) 'extend the array to the number of errors
        myarray(errorc-1) = "Numer Listy" 'place the error message in the last index of the array, which you could get using UBound() too
    End If
    

    编辑

    根据您的评论,我查看了this page。我有点惊讶。从我看到它的位置,UBound 应该返回数组的大小 -1,但从给出的示例来看,它似乎返回数组的大小,点。因此,如果该页面上的示例是正确的(并且您的错误似乎表明它们是正确的),您应该这样编写循环:

    For i = LBound(myarray) To UBound(myarray)-1
        msg = msg & myarray(i) & vbNewLine
    Next i
    

    【讨论】:

    • 不知何故发生错误 For i = LBound(myarray) To UBound(myarray) msg​​ = msg & myarray(i) & vbNewLine Next i |||||下标超出范围
    • 你试过调试吗?它总是失败还是只有当你没有错误时?只需检查 i 的值和数组的大小。几乎可以肯定您正在尝试访问数组中不存在的索引。例如,当您的数组为空时,可能会发生这种情况......对不起,自从我完成任何 VB 以来已经太久了,我对此更加肯定:-)
    • 数组肯定不是空的:P 我不知道.. 还有其他方法可以制作一个带有空 txt/combo 字段的 msg 框吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多