Excel VBA循环通过01.Month和01.01。 给予最小和最大天数

所以我有一个最小和最大date存储为Date对象。 我尝试在for循环中迭代它们。

 Sub dateTest() Dim min_date As Date Dim max_date As Date min_date = ThisWorkbook.Worksheets("setup").Cells(22, 5).value max_date = ThisWorkbook.Worksheets("setup").Cells(23, 5).value Dim currentDate As Date For currentDate = min_date To max_date MsgBox (currentDate) Next End Sub 

然而,每个月的每一天都会显示一个周期,而我只需要每个月的第一天和(另一个周期)只有一月份的第一天。 我将如何做到这一点?

我试过了

 For currentDate = min_date To max_date Step 7 MsgBox (currentDate) Next 

但是它只允许把日子作为一个步骤,所以这个代码每周显示一天,而不是每个月每天或每年一天。

此代码将从包含min_date的月份的第一天到包含max_date的月份的第一天干净地循环:

 Sub dateTest() Dim min_date As Date Dim max_date As Date Dim firstOfMonth As Date Dim lastFirstOfMonth As Date With ThisWorkbook.Worksheets("setup") min_date = .Cells(22, 5).Value max_date = .Cells(23, 5).Value End With firstOfMonth = DateSerial(Year(min_date), Month(min_date), 1) lastFirstOfMonth = DateSerial(Year(max_date), Month(max_date), 1) Do While firstOfMonth <= lastFirstOfMonth MsgBox firstOfMonth firstOfMonth = DateAdd("m", 1, firstOfMonth) Loop End Sub 

如果您想让消息框显示每个月的第一天,则可以检查date是否为1(每月的第一天)。

 For currentdate = min_date To max_date If Day(my_date) = 1 Then MsgBox (my_date) Else 'Do Nothing End If Next 

这将返回每个月的第一个消息框。

要显示1月份的第一个月份,请检查月份。

 For currentdate = min_date To max_date If Month(currentdate) = 1 Then If Day(currentdate) = 1 Then MsgBox (currentdate) End If Else 'Do Nothing End If Next 

DateAdd函数应该有助于:

假设你的最短date总是在本月的第一天:

 Dim currentDate As Date currentDate = min_date Do Until currentDate >= max_date currentDate = DateAdd("m", 1, currentDate) ' Adds 1 month to the date ' Use DateAdd("yyyy", 1, currentDate) for adding 1 year. MsgBox currentDate Loop 

如果您的最短date不在当月的第一天,请将“currentDate = min_date”行replace为

 currentDate = GetNextFirstDayOfMonth(min_date) 

并添加以下function:

 Function GetNextFirstDayOfMonth(d) If Day(d) > 1 Then GetNextFirstDayOfMonth = DateSerial(Year(d), Month(d), 1) Else GetNextFirstDayOfMonth = DateSerial(Year(d), Month(d) - 1, 1) End If End Function