简体   繁体   English

EXCEL VBA-有2个日期的While循环

[英]EXCEL VBA - Do While loop with 2 dates

Working on populating a row in excel with dates between a start date and current date. 在Excel中用开始日期和当前日期之间的日期填充行。 The population is weekly and below is the function I have made. 人口是每周一次,以下是我的职能。 It works fine up until the point where it doesn't stop but continues to go infinitely until there is an overflow error hence my assumption is that CurrentDate is not working properly. 它可以正常工作直到不停止,直到出现溢出错误,然后继续无限运行,因此我认为CurrentDate无法正常工作。

The 2 dates used are StartDate = 04/1/2016 and CurrentDate = 12/07/2017 . 使用的2个日期是StartDate = 04/1/2016CurrentDate = 12/07/2017 StartDate = 04/1/2016

Any help or suggestions would be greatly appreciated. 任何帮助或建议,将不胜感激。

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

If you decide you need to maintain the value of StartDate (eg to use later in the code), you could replace your loop with: 如果您决定需要保持StartDate的值(例如,在代码的后面使用),则可以将循环替换为:

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

After looking at this myself I realized I wasn't increasing the startdate hence the loop was infinite. 自己看完之后,我意识到我没有增加开始日期,因此循环是无限的。 Thanks to @Nathan_Sav for pointing this out in the comments too. 感谢@Nathan_Sav在注释中也指出了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM