Ms access &引用;下标超出范围“;在VBA数组上调用LBound()或UBound()时出错
下面的代码产生错误“下标超出范围”,我不知道原因。有人能解释一下吗Ms access &引用;下标超出范围“;在VBA数组上调用LBound()或UBound()时出错,ms-access,vba,Ms Access,Vba,下面的代码产生错误“下标超出范围”,我不知道原因。有人能解释一下吗 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
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
我的VB(A)很遥远,但仍然是。(Re)Dim()
方法定义数组的大小;数组的索引从0变为大小1。因此,当您这样做时:
errorc = 1
If Len(Me.txt_Listnum) = 0 Then
ReDim Preserve myarray(errorc)
myarray(errorc) = "Numer Listy"
errorc = errorc + 1
End If
ReDim Preserve myarray(error c)
)。它将只有1个索引:0myarray(errorc)=“numeristy”
),这将失败,并显示您提到的错误消息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
编辑
听了你的话,我看了一眼。我有点惊讶。从我看到的地方,UBound应该返回数组的大小-1,但从给出的示例来看,它似乎返回数组的大小,point。因此,如果该页面上的示例是正确的(并且您的错误似乎表明它们是正确的),您应该这样编写循环:
For i = LBound(myarray) To UBound(myarray)-1
msg = msg & myarray(i) & vbNewLine
Next i
如果填充了所有表单控件,则代码将失败,因此
myarray
永远不会获得ReDim
'd。对于统一化的动态数组
Dim myarray() As Variant
(即,未随后使用ReDim调整大小的文件),在其上调用
LBound()
或UBound()
将因“下标超出范围”而失败。不知何故,i=LBound(myarray)到UBound(myarray)msg=msg&myarray(i)会出现错误&vbNewLine Next i|||||下标超出范围您尝试过调试吗?它总是失败,还是只有在你没有错误的时候才失败?只需检查i的值和数组的大小。几乎可以肯定,您正在尝试访问数组中不存在的索引。它可能发生在数组为空时,例如。。。对不起,我已经很久没用VB了,所以我对这个问题没有更多的肯定:-)数组肯定不是空的:P我不知道。。有没有其他方法可以创建包含空txt/combo字段的消息框?@user3002600将For
循环放入If error…
块中,并检查error>1
,而不是0
。