EXCEL VBA – Do While循环与2date

在excel中使用开始date和当前date之间的date填充行。 人口是每周和以下是我所做的function。 它的工作正常,直到它不停止,但继续无限的点,直到有一个溢出错误,因此我的假设是CurrentDate不能正常工作。

使用的两个date是StartDate = 04/1/2016CurrentDate = 12/07/2017 StartDate = 04/1/2016

任何帮助或build议将不胜感激。

 Public Function PopulateStartOfWeekDates() Dim wsCRC As Worksheet Set wsCRC = Worksheets("CRC") Dim StartDate As Date Dim CurrentDate As Date StartDate = FirstMondayOfYear() CurrentDate = Date Dim WeekOffset As Integer Dim i As Integer i = 12 WeekOffset = 0 Debug.Print StartDate Debug.Print CurrentDate Do While StartDate < CurrentDate wsCRC.Cells(5, i) = StartDate + WeekOffset wsCRC.Cells(5, i).EntireColumn.AutoFit i = i + 1 WeekOffset = WeekOffset + 7 Loop End Function 

如果您决定需要维护StartDate的值(例如稍后在代码中使用),则可以用以下代码replace您的循环:

 i = 0 Do While StartDate + i * 7 < CurrentDate wsCRC.Cells(5, i + 12) = StartDate + i * 7 wsCRC.Cells(5, i + 12).EntireColumn.AutoFit i = i + 1 Loop 

看着这个我自己,我意识到我没有增加startdate因此循环是无限的。 感谢@Nathan_Sav在评论中也指出了这一点。