您能帮我解决这个问题吗, 如果Excel工作表具有日期值,则每当我要调用我定义的数组的Ubound或Lbound时,都会出现一个错误,称为“下标超出范围”。我在VBA中编写的特定代码如下:
Sub conditiondate()
Dim i As Integer
Dim WS As Worksheet
Dim WB As Workbook
Dim Proinv As Workbook
Dim ProinvPath As String
Dim Proinvtemp As Workbook
Dim arrFlight() As Variant
Dim NewArray2 As Variant
Dim lngIndex2 As Integer
Dim lngNItems2 As Integer
Dim n As Integer
'Dim newarr As Variant
Dim j As Integer
Set WB = Application.ActiveWorkbook
startingdate = Worksheets(1).Range("C3") 'From
endingdate = Worksheets(1).Range("C4") 'To
For Each WS In Worksheets
i = 1
j = 0
Do
i = i + 1
j = j + 1
If WS.Cells(i + 10, 3) >= startingdate And WS.Cells(i + 10, 3) <= endingdate Then
WS.Cells(i + 10, 3).Font.Color = vbRed
WS.Cells(i + 10, 3).Offset(0, 13) = "issued"
ReDim Preserve arrFlight(j)
arrFlight(j) = WS.Cells(i + 10, 3).Value
Else
WS.Cells(i + 10, 3).Font.Color = vbBlue
End If
Loop Until i = 200
MsgBox UBound(arrFlight) ' <<---SCRIPT OUT OF RANGE EMERGED HERE**
Next WS
end Sub
感谢您的帮助
答案 0 :(得分:0)
为防止运行时错误9,您可以检查是否已分配了阵列,并在这种情况下显示MsgBox
If IsArrayAllocated(arrFlight) Then
MsgBox UBound(arrFlight) ' <<---SCRIPT OUT OF RANGE EMERGED HERE**
End If
我使用了发现here
的函数IsArrayAllocatedFunction IsArrayAllocated(Arr As Variant) As Boolean
On Error Resume Next
IsArrayAllocated = IsArray(Arr) And _
Not IsError(LBound(Arr, 1)) And _
LBound(Arr, 1) <= UBound(Arr, 1)
End Function
更新从上面提供的链接中引述,以解释失传
有两种类型的数组:静态数组,其中维 数组的设置在Dim语句中,动态数组在 使用ReDim语句分配和确定数组的大小。 如果消耗内存,具有有效的数组,则称该数组已分配 下界和上限,并包含数据(即使该数据是 数组数据类型的默认值,例如空字符串 字符串类型变量的数组)。根据定义,静态数组是 总是分配。您永远都不能调整大小,重新分配,取消分配或 释放静态数组消耗的内存。有了动态数组, 但是,您可以重新调整,重新分配,释放和释放 数组的内存。 (包含数组的Varaint类型变量 始终包含一个动态数组。)