Excel VBAで年、月、日から、指定した日付や○年後、○月後、○日後、○年前、○月前、○日前などの日付を取得したい時の記録です。
Excel VBAで年、月、日から日付を取得するには「DateSerial」関数を使います。
< スポンサーリンク >
「DateSerial」関数構文
指定した年、月、日の日付を返します。
DateSerial(year, month, day)
year = 必須。100以上9999以下の数値、または数式で指定
month = 必須。1以上12以下の数値、または数式で指定
day = 必須。1以上31以下の数値、または数式で指定
例
年を2019、月を6、日を13で指定して日付を取得します。
Sub test()
Dim hi As Date
hi = DateSerial(2019, 6, 13)
Debug.Print hi
End Sub
今日の日付から1年後を取得します。
Sub test()
Dim hi As Date
Dim kyou As Date
kyou = Date
hi = DateSerial(Year(kyou) + 1, Month(kyou), Day(kyou))
Debug.Print hi
End Sub
今日の日付から2ヶ月後を取得します。
Sub test()
Dim hi As Date
Dim kyou As Date
kyou = Date
hi = DateSerial(Year(kyou), Month(kyou) + 2, Day(kyou))
Debug.Print hi
End Sub
今日の日付から7日前を取得します。
Sub test()
Dim hi As Date
Dim kyou As Date
kyou = Date
hi = DateSerial(Year(kyou), Month(kyou), Day(kyou) – 7)
Debug.Print hi
End Sub
今月の末日を取得します。
※dayの「1-1」は「0」でも同じ結果になります。
Sub test()
Dim hi As Date
Dim kyou As Date
kyou = Date
hi = DateSerial(Year(kyou), Month(kyou) + 1, 1 – 1)
Debug.Print hi
End Sub
こんな記事も書いています