VBA関係

VBAのシステム管理してて困ったこととかサンプルコードとか書いてます。

VBA サンプルコード 日付の取得とか

主に日付関係のサンプルコードです。

 

'今日の日付と今の時間

Sub test1()

    Dim d as Date

    d = Now

    Call MsgBox(d)

End Sub

 

'今日の日付

Sub test2()

    Dim d as Date

    d = Date

    Call MsgBox(d)

End Sub

 

'今の時間

Sub test3()

    Dim d as Date

    d = Time

    Call MsgBox(d)

End Sub

 

'文字列から日付を生成

Sub test4()

    Dim d as Date

    d = CDate("2024/3/19")

    Call MsgBox(d)

End Sub

 

'翌年の今日を取得

Sub test5()

    Dim d as Date

    d = DateAdd("yyyy", 1, Date)

    Call MsgBox(d)

End Sub

 

'翌月の今日を取得

Sub test6()

    Dim d as Date

    d = DateAdd("m", 1, Date)

    Call MsgBox(d)

End Sub

 

'明日を取得

Sub test7()

    Dim d as Date

    d = DateAdd("d", 1, Date)

    Call MsgBox(d)

End Sub

 

'任意の日を取得

Sub test8()

    Dim d as Date

    d = DateSerial(2024, 3, 19)

    Call MsgBox(d)

End Sub

 

'年を取得

Sub test9()

    Dim y as Long

    y = Year(Date)

    Call MsgBox(y)

End Sub

 

'月を取得

Sub test10()

    Dim m as Long

    m = Month(Date)

    Call MsgBox(m)

End Sub

 

'日を取得

Sub test11()

    Dim d as Long

    d = Day(Date)

    Call MsgBox(d)

End Sub

 

'Formatで文字列に変換

Sub test12()

    Dim s as String

    s = Format(Date, "yyyy年m月d日")

    Call MsgBox(s)

End Sub

 

Formatについては色々な使い方があるっぽいです。「VBA Format関数」で検索すると出てきますので、興味がある方はぜひ。