我一直在尝试编写一小段代码来验证以确认数组中是否包含日期。我已经能够滚动代码,直到If lists(i) = TodaysDate Then
显示lists(i)
时我到达subscript out of range
行。我在互联网上搜索过,我无法解决这个问题。
My Macro内容如下:
Sub size_an_array()
Dim i As Integer
Dim Range_of_Dates As Integer
Dim TodaysDate As Variant, finish As String
TodaysDate = Range("Sheet11!c2")
ThisWorkbook.Worksheets("Sheet11").Activate
lists = Range("Processed_Dates")
Range_of_Dates = UBound(lists, 1) - LBound(lists, 1) + 1
For c = 1 To UBound(lists, 1) ' First array dimension is rows.
For R = 1 To UBound(lists, 2) ' Second array dimension is columns.
Debug.Print lists(c, R)
Next R
Next c
x = Range_of_Dates 'UBound(lists, 1)
ReDim lists(x, 1)
i = 1
Do Until i = x
If lists(i) = TodaysDate Then
Exit Do
End If
Loop
MsgBox "The date has not been found"
End Sub
我对VBA
相对较新,我一直在尝试使用命名范围来拉入阵列但是我完全在试图解决这个问题时完全处于最后的位置。
非常感谢任何帮助。
答案 0 :(得分:2)
您已将数组lists
从一维数组重新调整为二维数组,然后您尝试在可疑行(下方)中仅使用一个维度引用元素,这会导致您的错误。
If lists(i) = TodaysDate Then
作为参考,Run-time error 9: Subscript out of range
表示您正在引用不存在的数组元素。
答案 1 :(得分:0)
我认为这是你在尝试的?
Sub size_an_array()
Dim i As Integer
Dim TodaysDate As Variant, lists
Dim bFound As Boolean
'~~> Change SomeWorksheet to the relevant sheet
TodaysDate = Sheets("SomeWorksheet").Range("c2")
lists = Sheets("Sheet11").Range("Processed_Dates")
i = 1
Do Until i = UBound(lists)
If lists(i, 1) = TodaysDate Then
bFound = True
Exit Do
End If
i = i + 1
Loop
If bFound = True Then
MsgBox "The date has been found"
Else
MsgBox "The date has not been found"
End If
End Sub
如果我理解正确,那么使用.Find
要容易得多。如果您有兴趣,请查看此link。