生成一个给定开始和结束date的date列表

之前,我发现Andy Brown做的一些VBA代码生成一个列表,并使每个date都是第一个或第十五个用户。 我试图调整这个代码,以满足我的需求,但我很挣扎。 目前的代码,一旦运行,只是在相同的date一遍又一遍地结束,我不得不结束Excel。

Sub GenerateDates() Dim FirstDate As Date Dim LastDate As Date Dim NextDate As Date FirstDate = Range("A1").Value LastDate = Range("a2").Value NextDate = FirstDate Range("B1").Select Do Until NextDate >= LastDate ActiveCell.Value = NextDate ActiveCell.Offset(1, 0).Select If Day(NextDate) = 1 Then NextDate = DateAdd("d", NextDate, 14) Else NextDate = DateAdd("d", NextDate, 20) NextDate = DateSerial(Year(NextDate), Month(NextDate), 1) End If Loop 

之前的代码我基于我的模型在上面列出,我的,很可能是可怕的代码如下:

 Sub GenerateDates() Dim FirstDate As Date Dim LastDate As Date Dim NextDate As Date FirstDate = Range("startdate").Value LastDate = Range("enddate").Value NextDate = FirstDate Range("tripdays").Select 'selection of columns within one row Do Until NextDate >= LastDate ActiveCell.Value = NextDate ActiveCell.Offset(1, 0).Select If Day(NextDate) = 1 Then NextDate = DateAdd("d", NextDate, 14) End If Loop End Sub 

我需要的是在给定的开始date和结束date之间生成每个date,而不是仅仅是第15和第1日。 这是怎么做的?

编辑:

这显然是你需要的,正如评论中所讨论的那样。

 Sub GenerateDates() Dim FirstDate As Date Dim LastDate As Date Dim NextDate As Date FirstDate = Range("startdate").Value LastDate = Range("enddate").Value NextDate = FirstDate Range("tripdays").Select 'selection of columns within one row Do Until NextDate > LastDate ActiveCell.Value = NextDate ActiveCell.Offset(1, 0).Select NextDate = NextDate + 1 Loop End Sub 

或者, For循环也可以。

截图:

在这里输入图像说明

进一步编辑:

水平版本,按要求。

 Sub GenerateDatesH() Dim FirstDate As Date Dim LastDate As Date Dim NextDate As Date Dim DateOffset As Range Dim DateIter As Date FirstDate = Range("startdate").Value LastDate = Range("enddate").Value Set DateOffset = Range("tripdays") For DateIter = FirstDate To LastDate DateOffset.Value = DateIter Set DateOffset = DateOffset.Offset(0, 1) Next DateIter End Sub 

截图:

在这里输入图像描述

注意:我也修复了垂直版本在提供的结束date停止。

避免在代码中使用select是非常低效的:)

 Sub p() Dim FirstDate As Date Dim LastDate As Date Dim NextDate As Date Dim r As Long FirstDate = Range("A1").Value LastDate = Range("a2").Value r = 1 Do FirstDate = FirstDate + 1 Cells(r, 2) = FirstDate r = r + 1 Loop Until FirstDate = LastDate End Sub 

(1,r)replace单元格(r,2),并开始r = 2