日付の加算を行うDateAdd関数

日付

DateAdd関数

 DateAdd関数は、引数で指定した時間間隔で日付の加算を行う関数です。
 戻り値はバリアント型ですが、ほとんどの場合Date型で受けることができます。

 閏年や月末、曜日などカレンダーを考慮した指定ができるため、1月をまたいだ日付指定、大の月、小の月を考慮した月末指定など日付固有の計算が簡単にできます。

構文

 構文は以下の通りです。

 DateAdd(interval, number, date)

 引数は省略できません。

interval
 時間間隔を指定文字列で指定します。

  指定文字列     意 味   
yyyy
四半期
m
年間通算日
平日
ww

number
 追加する値を整数で指定します。負の値もOKですが、少数は整数値に丸められます。

date
 起点となる日付・時間をセットします。

サンプルコード

 いくつかサンプルコードを挙げておきます。

10日後の日付

Sub test()
    Debug.Print DateAdd("d", 10, #1/24/2022#)
End Sub

結果:2022/02/03

閏年をリストアップ

'2023年以降の閏年(10年分)
Sub testDateAdd()

    Dim startDay As Date, myDate As Date
    Dim i As Long
    
    startDay = #3/1/2022#
        
    For i = 1 To 9
        myDate = DateAdd("yyyy", i, startDay) - 1
        If Day(myDate) = 29 Then
            Debug.Print myDate
        End If
    Next i
End Sub

結果:
2024/02/29
2028/02/29

月末の日付をリストアップ

'月末の日付を取得
Sub testDateAdd2()
    Dim startDay As Date, myDate As Date
    Dim i As Long
    
    startDay = #1/1/2022#
        
    For i = 1 To 12
        myDate = DateAdd("m", i, startDay) - 1
        Debug.Print myDate
    Next i
End Sub

結果:
2022/01/31
2022/02/28
2022/03/31
2022/04/30
2022/05/31
2022/06/30
2022/07/31
2022/08/31
2022/09/30
2022/10/31
2022/11/30
2022/12/31

コメント

タイトルとURLをコピーしました