Question

I was trying to do the following:

startDate = Date
endDate = DateAdd("yyyy", -1, startDate)

currentDate = startDate
Do While DateDiff("d", endDate, currentDate) <> 0
    With ActiveSheet.Range("A1")
        .Offset(i, 0).Value = currentDate
    End With
    currentDate = DateAdd("d", -1, currentDate)
    i = i + 1
Loop

to loop from startDate to endDate and output every date in between. After the first iteration currentDate equals the minimum date (1899). I know there are other ways to do this and I have a way that works now, but why does this fail?

Was it helpful?

Solution

Your code worked fine for me

Yoo could actually avoid the loop by either

  • adding a worksheet function to the time span of interest
  • dumping a function to a variant array direct to the sheet (as below)

code

Sub Test2()
Dim x
Dim dtStart As Date
Dim lngStart As Long
'test for leap year
lngStart = 365
If Year(Now()) Mod 4 = 0 Then
If Year(Now()) Mod 25 = 0 Then lngStart = lngStart + 1
End If

dtStart = Date
x = Application.Evaluate("NOW()-row(1:" & lngStart & ")+1")
With [a1].Resize(UBound(x, 1), 1)
.Value = x
.NumberFormat = "d/mm/yyyy;@"
End With
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top