IF,Else,ElseIF在特定日期内循环

时间:2015-10-30 06:55:32

标签: excel vba loops

我想设置以下条件,但我只能完成2个条件

三个条件小于7天,一个值乘以一个值,两个日期之间的范围乘以一个值,超过30天乘以另一个值。

无法全部工作

不确定出了什么问题

' To create the following condition
 'If less than 7 days interest = 0%
' if 8 to 30 days interest = 7%
 'if more than 31 days interest = 9%

Sub Workbook_Open()

For i = 1 To 3 'Rows.Count
xdate = Cells(i, 1)

nulldate = DateAdd("d", -7, Date)
irate7late = DateAdd("d", -8, Date)
irate7early = DateAdd("d", -30, Date)


If Day(nulldate) < Day(xdate) Then
    result = Cells(i, 2) * 1
ElseIf Day(irate7early) <= Day(xdate) And Day(xdate) <= Day(irate7late) Then
            '30/9/2015      20/10/2015      20/10/2015      22/10/2015
    result = Cells(i, 2) * 1.07

ElseIf Day(irate7early) > Day(xdate) Then
    result = Cells(i, 2) * 1.09
End If

Cells(i, 3).Value = result

Next i

End Sub

2 个答案:

答案 0 :(得分:1)

逆转你的测试有时可能会简化它们:

Sub Workbook_Open()

    Dim delta as Long
    Dim xdate as Date
    For i = 1 To 3 'Rows.Count
        xdate = Cells(i, 1).Value
        delta = DateDiff("d", xdate, Date)

        If delta > 30 Then
            Cells(i,3).Value = Cells(i,2).Value * 1.09
        ElseIf delta > 7 Then
            Cells(i,3).Value = Cells(i,2).Value * 1.07
        Else 'delta <= 7
            Cells(i,3).Value = Cells(i,2).Value
        End If
    Next i

End Sub

不要忘记Option Explicit,它可以节省你很多时间进行调试。

答案 1 :(得分:0)

根据您的要求尝试以下代码

 Sub Workbook_Open()

Dim diffdate As Variant

For i = 1 To 3 'Rows.Count

      xdate = Cells(i, 1).Value
      diffdate = (DateDiff("d", xdate, Now()))

        If diffdate < 7 Then
            result = Cells(i, 2) * 1
        ElseIf diffdate < 31 And diffdate > 7 Then
            result = Cells(i, 2) * 1.07
        Else
            result = Cells(i, 2) * 1.09
        End If

    Cells(i, 3).Value = result

Next

End Sub