将项目添加到数组VBA excel

我想添加date到一个数组,但不能做到这一点。 每次我尝试去做,我都会得到一个下标超出范围的错误。 我曾经在其他语言使用过数组,所以这应该工作,但它不是,我似乎不明白为什么。 下面我添加了目前无法使用的代码。 我想要做的是在用户input两个date后,我的代码应该存储的起始值,然后添加一个该date,并将其添加到数组等,直到我有一个数组列表中的所有date从开始date到结束date。 任何帮助将是非常感谢

Private Sub SearchButton4_Click() Dim wks As Excel.Worksheet, str1, str2, str3, str4 As Date, x As Integer Dim dateArray() As Date ReDim dateArray(1 To 1) As Date Set wks = Worksheets("Exceptions") str1 = Format(DateFromTextBox.Value, "dd-mm-yyyy") str3 = Format(DateToTextBox.Value, "dd-mm-yyyy") str2 = DateDiff("d", str1, str3) If str2 < 0 Then str2 = str2 * -1 End If For x = 0 To str2 If x = 0 Then dateArray(x) = str1 Else str4 = DateAdd("d", 1, str1) dateArray(x) = str4 str1 = str4 End If Next End Sub 

下面尝试,redim将调整数组的大小。 ubound()查找数组的顶端,所以ubound()+ 1将为数组添加一个额外的大小。 preserve关键字将保留当前在数组中的任何值

注意1:我如何声明variablesstr1 – 3没有被声明为date。 2:我如何初始化你的数组不需要做1对1就可以说我想要x的数量

希望有所帮助

 Private Sub SearchButton4_Click() Dim wks As Excel.Worksheet, str1 As Date, str2 As Date, str3 As Date, str4 As Date, x As Integer Dim dateArray() As Date ReDim dateArray(1) As Date Set wks = Worksheets("Exceptions") str1 = Format(DateFromTextBox.Value, "dd-mm-yyyy") str3 = Format(DateToTextBox.Value, "dd-mm-yyyy") str2 = DateDiff("d", str1, str3) If str2 < 0 Then str2 = str2 * -1 End If For x = 0 To str2 If x = 0 Then dateArray(x) = str1 Else str4 = DateAdd("d", 1, str1) dateArray(x) = str4 str1 = str4 End If ReDim Preserve dateArray(ubound(dateArray)+1) Next End Sub 

你需要增加数组的大小。 这一行:

 ReDim dateArray(1 To 1) As Date 

只给你数组中的一个元素。 你应该使用:

 ReDim dateArray(0 To str2) As Date 

在你计算出str2的值之后。

顺便说一句,你可以使用Abs函数给你一个正数:

 str2 = Abs(DateDiff("d", str1, str3)) 

另外,当你在一行中声明多个variables时,你必须包含每个variables的types。 在这一行中:

 Dim wks As Excel.Worksheet, str1, str2, str3, str4 As Date, x As Integer 

variablesstr1, str2, str3都被声明为Variant not Date

原因是你已经声明数组dateArray只有一个元素,索引1:

 ReDim dateArray(1 To 1) As Date 

后来在你的代码中,你尝试给索引为0的这个数组的一个元素赋值(但是没有这样的元素,这就是显示这个错误的原因):

 For x = 0 To str2 If x = 0 Then dateArray(x) = str1 '<---- in first iteration, when x = 0, you ' try to assign to element with 0 index. Else (...) 

您已经计算了大小,所以您可以使用Redim一次,而不是使用Preserve ,这是一个相对昂贵的操作,因为它会复制整个arrays。 我也build议一些更具描述性的variables名称,你应该明确声明所有variables的types:

 Private Sub SearchButton4_Click() Dim wks As Excel.Worksheet Dim dtFrom As Date Dim dtTo As Date Dim lNumberOfDays As Long Dim x As Long Dim dateArray() As Date Set wks = Worksheets("Exceptions") dtFrom = CDate(DateFromTextBox.Value) dtTo = CDate(DateToTextBox.Value) If dtTo < dtFrom Then dtTo = CDate(DateFromTextBox.Value) dtFrom = CDate(DateToTextBox.Value) End If lNumberOfDays = dtTo - dtFrom ReDim dateArray(1 To lNumberOfDays + 1, 1 To 1) As Date For x = 0 To lNumberOfDays dateArray(x + 1, 1) = dtFrom + x Next With wks.Range("A1").Resize(UBound(dateArray)) .NumberFormat = "dd-mm-yyyy" .Value = dateArray End With End Sub 

我以为你会输出结果到工作表,所以我使用了二维数组。