在MS Access 2003 VBA中调用全局对象数组上的LBound()和UBound()函数时,我收到“下标超出范围”错误。我不明白为什么会发生这种情况,因为我确定数组已经初始化,因为我可以通过引用数组的已知索引来访问数组中的值。
这是我的类,它有一个字符串数组作为属性。我正在初始化数组Class_Initialize方法。
Private pIgnoreDifferencesInDatabaseComparisonForFields() As String
Public Property Get ignoreDifferencesInDatabaseComparisonForFields() As String()
ignoreDifferncesInDatabaseComparisonForFields = pIgnoreDifferencesInDatabaseComparisonForFields
End Property
Public Property Get ignoreDifferencesInDatabaseComparisonForField(index As Long) As String
ignoreDifferencesInDatabaseComparisonForField = pIgnoreDifferencesInDatabaseComparisonForFields(index)
End Property
Public Property Let ignoreDifferencesInDatabaseComparisonForField(index As Long, fld As String)
If index > UBound(pIgnoreDifferencesInDatabaseComparisonForFields) Then ReDim Preserve pIgnoreDifferencesInDatabaseComparisonForFields(index)
pIgnoreDifferencesInDatabaseComparisonForFields(index) = fld
End Property
Private Sub Class_Initialize()
Dim ignoreDiffInDBComparisonForFields() As String
Dim i As Long
' Add any new columns to skip inside this string
ignoreDiffInDBComparisonForFields = Split("EligOvr,UpdateTS,groupStartDate,groupEndDate", ",")
ReDim pIgnoreDifferencesInDatabaseComparisonForFields(0)
For i = LBound(ignoreDiffInDBComparisonForFields) To UBound(ignoreDiffInDBComparisonForFields)
Me.ignoreDifferencesInDatabaseComparisonForField(i) = ignoreDiffInDBComparisonForFields(i)
Next i
End Sub
我在任何函数或子函数之外的主模块顶部将对象声明为全局变量。
Public settings As Options
然后,在我调用的主函数中,我有以下代码行。
Set settings = New Options
稍后在我的代码中,调用此函数。
Function isAnIgnoreDifferencesInDatabaseComparisonField(field As String) As Boolean
Dim found As Boolean
Dim i As Long
found = False
x = settings.ignoreDifferencesInDatabaseComparisonForField(1)
For i = LBound(settings.ignoreDifferencesInDatabaseComparisonForFields) To UBound(settings.ignoreDifferencesInDatabaseComparisonForFields)
If (LCase(field) = LCase(settings.ignoreDifferencesInDatabaseComparisonForField(i))) Then
found = True
End If
Next i
isAnIgnoreDifferencesInDatabaseComparisonField = found
End Function
我在for循环中收到错误消息,我第一次点击“For i ...”行时调用UBound和LBound函数。它不会通过循环的任何迭代。我将x设置为数组中位置1的值作为测试,并且该值确实填充而没有错误,因此数组已经初始化。有谁知道为什么我得到“下标超出范围”错误?谢谢!
答案 0 :(得分:2)
你的问题在于:
Public Property Get ignoreDifferencesInDatabaseComparisonForFields() As String()
ignoreDifferencesInDatabaseComparisonForFields = pIgnoreDifferencesInDatabaseComparisonForFields
' ^ correct typo here ^
End Property
当我修复此问题时,您的代码已编译,并且在没有Subscript out of range
错误的情况下正常运行。
答案 1 :(得分:0)
我不能说我在Access中使用了很多VBA,但我知道它可以在Excel中做一些有趣的事情。我会尝试将上限设置为Ubound()-1,看看会发生什么。有时VBA使用标准惯例Start at 0-9,其他时间从1开始,具体取决于对象类型。
同样作为最终for循环中的一方,如果找到匹配,您可能需要考虑添加Exit For。没有理由完成循环,如果它是真的。