在数组中处理数据时发生错误

我想确定B列中的date是否在几个时期中的两个date之间(第m月的第一天和第m- 1年的第n + 1天的最后一天)。 例如,2013年9月20日,列B中的单元值是否落在:

7/1/2010 and 6/30/2011 7/1/2011 and 6/30/2012 7/1/2012 and 6/30/2013 7/1/2013 and 6/30/2014 7/1/2015 and 6/30/2016 

如果为True,则列C的同一行中的单元格值将包含date落在的结束期间的年份(在本例中为2014),如果为False ,将返回空白单元格。 以下是我需要检查的B列中的数据:

 9/11/2013 8/20/2015 8/22/2013 8/31/2001 (Blank cell) 8/31/2009 AAA 9/3/2013 (Blank cell) 9/25/2011 9/30/2013 10/10/2012 Anna 10/4/2015 

首先我用下面的代码进行了检查:

 Sub CheckMyYear1_Click() Dim i As Long, j As Long, Last_Row As Long, Period As Long T0 = Timer Last_Row = Cells(Rows.Count, "B").End(xlUp).Row Period = 5 For j = 2 To Last_Row For i = 1 To Period Begin_Period = DateSerial(Year(Date) - i, Month(Date), 1) End_Period = DateSerial(Year(Date) - i + 1, Month(Date), 0) If Cells(j, "B") >= Begin_Period And Cells(j, "B") <= End_Period Then Cells(j, "C") = Year(End_Period) Exit For End If Next i If Cells(j, "C") = "" Then Cells(j, "C") = "Out of Period" Cells(j, "C").Font.Color = RGB(226, 107, 10) End If If Cells(j, "B") = "" Then Cells(j, "C") = "No Data" Cells(j, "C").Font.Color = vbRed ElseIf IsDate(Cells(j, "B").Value) = False Then Cells(j, "C") = "Not Date" Cells(j, "C").Font.Color = vbRed End If Next j Range("C2:C" & Last_Row).Copy InputBox "The runtime of this program is ", "Runtime", Timer - T0 End Sub 

它工作正常,并返回正确的输出。 为了提高性能,因为数据集的大小可能很大,我将数据集存储在一个数组中,并循环遍历数组来检查它的每个元素。 这是我使用的代码:

 Sub CheckMyYear2_Click() Dim i As Long, j As Long, Last_Row As Long, Period As Long T0 = Timer Last_Row = Cells(Rows.Count, "B").End(xlUp).Row Period = 5 ReDim MyDate(2 To Last_Row, 1 To 1) ReDim MyYear(2 To Last_Row, 1 To 1) MyDate = Range("B2:B" & Last_Row).Value For j = 2 To Last_Row For i = 1 To Period Begin_Period = DateSerial(Year(Date) - i, Month(Date), 1) End_Period = DateSerial(Year(Date) - i + 1, Month(Date), 0) If MyDate(j, 1) >= Begin_Period And MyDate(j, 1) <= End_Period Then MyYear(j, 1) = Year(End_Period) Exit For End If Next i If MyYear(j, 1) = "" Then MyYear(j, 1) = "Out of Period" Cells(j, "C").Font.Color = RGB(226, 107, 10) End If If MyDate(j, 1) = "" Then MyYear(j, 1) = "No Data" Cells(j, "C").Font.Color = vbRed ElseIf IsDate(MyDate(j, 1).Value) = False Then MyYear(j, 1) = "Not Date" Cells(j, "C").Font.Color = vbRed End If Next j Range("C2:C" & Last_Row).Value = MyYear Range("C2:C" & Last_Row).Copy InputBox "The runtime of this program is ", "Runtime", Timer - T0 End Sub 

运行时错误“9”使用上面的代码。 然后我打F8来知道箭头指向哪里,但箭头没有指向任何线。

有没有人知道如何解决这个错误? 我也有兴趣知道更好的方式来完成上述任务。

你的问题是,将一个范围分配给一个dynamic数组会改变每个维度的下限为1,即使你已经使用ReDim来设置其他的。 所以虽然这样:

 ReDim MyDate(2 To Last_Row, 1 To 1) 

只要你这样做,给你一个指定大小的数组:

 MyDate = Range("B2:B" & Last_Row).Value 

你的数组实际上是MyDate(1 to Last_Row - 1, 1 to 1)