VBA Date + For logic

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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

回答1:

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 


文章来源: VBA Date + For logic
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!