EXCEL VBA - Do While loop with 2 dates

时间:2017-07-12 07:59:46

标签: excel vba excel-vba

Working on populating a row in excel with dates between a start date and current date. 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.

The 2 dates used are StartDate = 04/1/2016 and CurrentDate = 12/07/2017.

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

2 个答案:

答案 0 :(得分:2)

如果您决定需要维护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

答案 1 :(得分:0)

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.