获取vba中2个date之间的所有date

我是一个新手在vba中,我想在vba中获取所有date之间的所有date,例如我将调用参数01-01-2015和15-01-2015函数,我会得到一个数组与所有date可能,即:

01-01-2015 02-01-2015 03-01-2015 ..... 15-01-2015 

我没有在论坛上find答案,所以在此先感谢您的帮助。

你可以简单地将date转换为长循环(+1),并在两个date之间获得所有date(将其转换为date)

 Sub Calling() Dim test test = getDates(#1/25/2015#, #2/5/2015#) End Sub Function getDates(ByVal StartDate As Date, ByVal EndDate As Date) As Variant Dim varDates() As Date Dim lngDateCounter As Long ReDim varDates(1 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 End Function 

也许这个。

 Function udf_Array_of_Dates(dtSTART As Date, dtEND As Date, rDATEs As Range) Dim dt() As Date, r As Range, d As Long For Each r In rDATEs If r.Value >= dtSTART And r.Value <= dtEND Then d = d + 1 ReDim Preserve dt(1 To d) dt(d) = r.Value End If Next r udf_Array_of_Dates = dt End Function 

certificate和语法:

用于数组的日期的UDF

包含从01-01-2015到15-01-2015的所有date的数组“sn”。 Msgbox介绍来说明结果。

 Sub M_snb() sn = Evaluate("index(text(datevalue(""01-01-2015"")+row(1:" & DateDiff("d", CDate("01-01-2015"), CDate("15-01-2015")) & ")-1,""dd-mm-yyyy""),)") MsgBox sn(1, 1) & vbLf & sn(2, 1) & sn(UBound(sn), 1) End Sub 

如果你只是想打印两个date之间的date在Excel中,那么我的build议是你在代码下面尝试。

 Sub DateFill() Dim Start_Date As Date Dim End_Date As Date Dim Number_Of_Days As Integer Start_Date = InputBox(prompt:="Enter the Start Date", Title:="Date Print", Default:="3/1/2013") End_Date = InputBox(prompt:="Enter the End Date", Title:="Date Print", Default:="3/23/2013") Range("A1").Value = Start_Date 'Range("B1").Value = End_Date Range("A1").Select Number_Of_Days = DateDiff("d", Start_Date, End_Date) ' Return Day Number_Of_Days = Number_Of_Days + 1 'Range("C1").Formula = "=DATEDIF(A1, B1, ""D"") " Selection.AutoFill Destination:=Range("A1:A" & Number_Of_Days), Type:=xlFillDefault Range("A1:A" & Number_Of_Days).Select End Sub 

在这里你可以避免使用Loop来节省执行时间。

从给定范围获取所有date的函数

 Function GetDatesRange(dateStart As Date, dateEnd As Date) As Collection Dim dates As New Collection Dim currentDate As Date currentDate = dateStart Do While currentDate <= dateEnd dates.Add currentDate currentDate = DateAdd("d", 1, currentDate) Loop Set GetDatesRange = dates End Function 

示例用法

 Dim dateStartCell as Range, dateEndCell as Range Dim allDates as Collection Dim currentDateSter as Variant Dim currentDate as Date Set dateStartCell = ActiveSheet.Cells(3, 3) Set dateEndCell = ActiveSheet.Cells(3, 6) Set allDates = GetDatesRange(dateStartCell.Value, dateEndCell.Value) For Each currentDateSter In allDates currentDate = CDate(currentDateSter) 'Do something with currentDate Next currentDateSter