要列出来自VBA代码的日期,请写出开始日期和结束日期,并按月递增

问题描述

这是我第一次在这里写,对此感到非常高兴,

现在我有一个excel文件,我尝试放置开始日期和结束日期,并在范围内键入此日期之间的日期...,以免产生示例

我尝试使用此代码

    Sub datetest()


Dim x,y,z,v,a,b As Range

Set x = Cells.Range("k2")
Set y = Cells.Range("l2")
Set z = Cells.Range("m2")
Set v = Cells.Range("n2")
Set a = Cells.Range("o2")
Set b = Cells.Range("p2")



Dim startDate As Date
Dim endDate As Date

startDate = DateSerial(x,z)
endDate = DateSerial(v,b)


Dim i As Integer
i = 1

While startDate <= endDate
    Cells(i,1) = startDate
    startDate = startDate + 31
    i = i + 1
Wend

End Sub

when i run the code,it type the dates good .

我的问题是,我现在添加31天,并且日期不正确,

我需要编辑代码以每次添加一个月,而不是像这样的一天

start date 1-3-2020
end date 1-3-2021

结果显示日期格式为ddd - mmm - yyyy

1-3-2020
1-4-2020
1-5-2020
1-6-2020
1-7-2020

然后继续直到

1-3-2021

再次感谢您的光临

解决方法

尝试一下:

Sub datetest()


Dim x,y,z,v,a,b As Range

Set x = Cells.Range("k2")
Set y = Cells.Range("l2")
Set z = Cells.Range("m2")
Set v = Cells.Range("n2")
Set a = Cells.Range("o2")
Set b = Cells.Range("p2")



Dim startDate As Date
Dim endDate As Date

startDate = DateSerial(x,z)
endDate = DateSerial(v,b)


Dim i As Integer
i = 1

While startDate <= endDate
    Cells(i,1) = startDate
    startDate = DateSerial(Year(startDate),Month(startDate) + 1,Day(startDate))
    i = i + 1
Wend

End Sub