将vba中2个日期之间的所有日期存储到数组中
我正在使用一个函数来获取开始日期和结束日期列表中 2 个日期之间的所有日期:我希望将从开始日期到结束日期的每个日期及其唯一 ID 存储在数组中。数据为列 1 ID、2 开始日期、3 结束日期。该数组将是一个 ID 列表,其中包含从开始日期到结束日期的所有相关日期。下面是我必须获取所有日期的代码:
Sub Test_Dates()
'
Dim TESTWB As Workbook
Dim TESTWS As Worksheet
Set TESTWB = ThisWorkbook
Set TESTWS = TESTWB.Worksheets("TEST")
For i = 2 To TESTWS.Cells(1, 1).End(xlDown).Row
DatesTest = getDates(TESTWS.Cells(i, 2), TESTWS.Cells(i, 3))
Next i
End Sub
Function getDates(ByVal StartDate As Date, ByVal EndDate As Date) As Variant
Dim varDates() As Date
Dim lngDateCounter As Long
ReDim varDates(0 To CLng(EndDate) - CLng(StartDate))
For lngDateCounter = LBound(varDates) To UBound(varDates)
varDates(lngDateCounter) = CDate(StartDate)
StartDate = CDate(CDbl(StartDate) + 1)
Next lngDateCounter
getDates = varDates
ClearMemory:
If IsArray(varDates) Then Erase varDates
lngDateCounter = Empty
I am using a function to get all dates between 2 dates in a list of Start Dates and End Dates: I am looking to store in an array each of the dates from start to end date with their unique ID. Data is column 1 ID, 2 Start Date, 3 End Date. The array would be a list of ID's with all pertaining dates from Start Date to End Date. Below is the code I have to get all dates:
Sub Test_Dates()
'
Dim TESTWB As Workbook
Dim TESTWS As Worksheet
Set TESTWB = ThisWorkbook
Set TESTWS = TESTWB.Worksheets("TEST")
For i = 2 To TESTWS.Cells(1, 1).End(xlDown).Row
DatesTest = getDates(TESTWS.Cells(i, 2), TESTWS.Cells(i, 3))
Next i
End Sub
Function getDates(ByVal StartDate As Date, ByVal EndDate As Date) As Variant
Dim varDates() As Date
Dim lngDateCounter As Long
ReDim varDates(0 To CLng(EndDate) - CLng(StartDate))
For lngDateCounter = LBound(varDates) To UBound(varDates)
varDates(lngDateCounter) = CDate(StartDate)
StartDate = CDate(CDbl(StartDate) + 1)
Next lngDateCounter
getDates = varDates
ClearMemory:
If IsArray(varDates) Then Erase varDates
lngDateCounter = Empty
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需创建一个具有
ReDim DatesTest(1 To LastRow - FirstRow + 1)
行大小的数组,然后用getDates
的结果填充该数组即可。然后,您可以使用
DatesTest(1)
访问getDates
的第一个结果,其中DatesTest(1)(1)
应该为您提供第一组。如果你想循环遍历所有这些,你可以这样做:
或者类似
这应该输出类似的内容
如果你想使用
ID(i,1)
作为键,那么你需要使用集合
而不是数组。然后,您可以使用
DatesTest(TESTWS.Cells(2, 1))
获取第一组日期和DatesTest(TESTWS.Cells(2, 1))(1)
> 会给你该组的第一个日期。Just create an array with the size of the rows
ReDim DatesTest(1 To LastRow - FirstRow + 1)
and fill that with your results fromgetDates
.You can then access the first result of
getDates
withDatesTest(1)
whereDatesTest(1)(1)
should give you the first date of the first set.If you want to loop through all of them you can do it like that:
or like
This should output something like
If you want to use the
ID(i,1)
as key then you need to use aCollection
instead of an array.Then you can use
DatesTest(TESTWS.Cells(2, 1))
to get the first set of dates andDatesTest(TESTWS.Cells(2, 1))(1)
would give you the first date of that set.