计算增加给定日期范围的时间

时间:2019-08-15 14:16:51

标签: excel vba loops excel-formula

我要计算给定间隔(例如, 6个月)的日期(向前)移动次数(给定日期范围)。


示例:

范围:

开始日期:2019/08/05

结束日期:2020/08/05

时间间隔: 6个月

  • 第一次:2019/08/05 + 6个月= 2020/02/05
  • 第二次:2020/02/05 + 6个月= 2020/08/05

在这种情况下,输出= 2


我想在特定的单元格中打印所需的输出。

我想使用以下语法构建VBA:

DateAdd(时间间隔,数字,日期)

Private Sub CommandButton1_Click()
    Dim FirstDate As Date    ' Declare variables.
    Dim IntervalType As Integer
    Dim Number As Integer
    Dim EndDate As Date
    Dim TempDate As Date

    Dim i As Integer

    IntervalType = "m" ' "m" specifies MONTHS as interval.

    FirstDate = Cells(1, 1).Value
    EndDate = Cells(1, 2).Value
    Number = Cells(1, 3).Value  ' "Number" For the syntax DateAdd.

    i = 1
    Do Until TempDate = EndDate
        TempDate= DateAdd(IntervalType, Number, FirstDate)
        i = i + 1
    Loop
    Range("D1").Value = i
End Sub

但是我遇到了这个错误:

VBA Error

1 个答案:

答案 0 :(得分:1)

您遇到的错误是因为您试图将String分配给Integer和Integer数据类型。将IntervalType更改为字符串。

Sub DateTest()
    Dim FirstDate As Date    ' Declare variables.
    Dim IntervalType As String
    Dim Number As Integer
    Dim EndDate As Date
    Dim TempDate As Date
    Dim i As Integer

    IntervalType = "m" ' "m" specifies MONTHS as interval.
    FirstDate = Cells(1, 1).Value
    EndDate = Cells(1, 2).Value
    Number = Cells(1, 3).Value  ' "Number" For the syntax DateAdd.

    ' If number is not greater than zero an infinite loop will happen.
    If Number <= 0 Then
        MsgBox "Number needs to be greater than 0", vbCritical
        Exit Sub
    End If

    i = 1
    Do Until TempDate = EndDate
       If i <= 1 Then
           TempDate = DateAdd(IntervalType, Number, FirstDate)
       Else
           TempDate = DateAdd(IntervalType, Number, TempDate)
        End If
        i = i + 1
        Debug.Print i
    Loop
    Range("D1").Value = i - 1
End Sub

此外,您正在运行一个无限循环,其中TempDate始终从FirstDate变量开始循环。

此外,如果您的Number小于或等于零,那么您将获得无限循环。

此外,Else摆脱了溢出错误。没有它,TempDate将在每次循环后重置。