VBA日期+逻辑

时间:2018-06-26 19:18:39

标签: excel vba date for-loop format

有人可以帮助我吗?看来我的逻辑完全没有用,因为它会在开始时间一直在12:00 AM返回我 这是我的代码

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

它一直在回报我

开始日期为12:00:00 AM

1 个答案:

答案 0 :(得分:2)

下面的代码已经过测试,可以正常工作。更新列表:

1)要引用工作表Thisworkbook.Sheets("Sheet1"),我将其变暗为ws
2)更新了totalrow计算方式
3)由于您仅根据IF语句的一个结果进行操作,因此您可以精简为1行。
4)添加Option Explicit来捕获诸如将totalrowrowtotal交换之类的错误(这也是也会捕获您的工作表引用错误)
5)调整了i的增量(默认为1,无需声明Step 1

这已经过测试,并且可以正常工作。

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