Home » excel » excel – VBA Date + For logic

excel – VBA Date + For logic

Posted by: admin May 14, 2020 Leave a comment

Questions:

can someone help me? It seems my for logic is not working at all because it keeps returning me 12:00AM for starttime
Here is my code

Sub forlogic()
    Dim i As Single
    Dim totalrow As Double
    Dim startdate As Date
    Dim mydate As Date

    totalrow = Sheet1.Range("A1", Sheet1.Range("A1").End(xlDown)).Rows.Count
    mydate = Date

    Debug.Print mydate

    mydate = mydate - 90

    Debug.Print mydate

    For i = 1 To i = rowtotal Step 2
        startdate = Format(Range("E" & i).Value, "short date")
        startdate = Format(Date, "mm/dd/yyyy")

        If mydate > startdate Then
            Range("M" & i).Value = "Expired"
        End If

        i = i + 1
    Next i
    Debug.Print startdate
End Sub

it keeps returning me

12:00:00 AM for startdate

How to&Answers:

Below code is tested and working as expected. List of updates:

1) To refer to sheet, Thisworkbook.Sheets("Sheet1") which I dimmed as ws
2) Updated totalrow calculation
3) Since you are only acting on one outcome of the IF statement, you can condense to 1 line.
4) Add Option Explicit to catch errors like swapping totalrow with rowtotal (This also would have caught your sheet reference error)
5) Adjusted the i increment (this defaults to 1, no need to state Step 1)

This is tested and working fine on my end.

Option Explicit

Sub forlogic()
Dim totalrow As Long, i As Long
Dim startdate As Date, mydate As Date
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")

totalrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
mydate = Date - 90

For i = 1 To totalrow
    startdate = Format(ws.Range("E" & i).Value2, "mm/dd/yyyy")
    If mydate > startdate Then ws.Range("M" & i).Value = "Expired"
Next i

End Sub