2

我一直在尝试编写一小段代码来验证以确认日期是否包含在数组中。我已经能够滚动浏览代码,If lists(i) = TodaysDate Then直到lists(i)显示subscript out of range. 我已通过 Internet 搜索,但无法解决此问题。

我的宏内容如下:

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,我一直在尝试使用命名范围来拉入数组,但我完全不知道如何解决这个问题。

任何帮助将不胜感激。

4

2 回答 2

2

您已将数组lists从一维数组重新调整为二维数组,然后您尝试仅使用可疑行(下方)中的一维来引用元素,这会导致您的错误。

If lists(i) = TodaysDate Then

作为参考,Run-time error 9: Subscript out of range意味着您正在引用一个不存在的数组元素。

于 2013-02-04T18:06:21.170 回答
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。如果您有兴趣,请查看此链接

于 2013-02-04T18:08:04.023 回答