今日はVBAで日付を扱う案件があった。
とりいそぎ、日付関連の関数で済ませたけれど、オブジェクトがあると楽だなと思ったのでクラスモジュールを作ってみた。
作り方
まずはクラスモジュールを挿入し、プロパティウインドウから名前をDateObjectに変えておく。
DateObjectモジュール内に以下のコードを張り付ける。
PublicValueAsDatePrivateSub Class_Initialize()Value=DateEndSubPublicFunction SetDateByYYYYMMDD(yyyymmdd AsString)Value=DateSerial(Left(yyyymmdd,4),Mid(yyyymmdd,5,2),Right(yyyymmdd,2))EndFunctionPublicPropertyGet ToString(string_format AsString)AsString ToString =format(Value, string_format)EndPropertyPublicPropertyGet Self()As DateObject Set Self =MeEndPropertyPublicPropertyGet FirstOfMonth()As DateObject WithNew DateObject .Value=DateValue(Me.ToString("yyyy/mm/01"))Set FirstOfMonth =.Self EndWithEndPropertyPublicPropertyGet MoveMonth(n AsLong)As DateObject WithNew DateObject .Value=DateAdd("m", n,Me.Value)Set MoveMonth =.Self EndWithEndPropertyPublicPropertyGet LastMonth()As DateObject Set LastMonth =Me.MoveMonth(-1)EndPropertyPublicPropertyGet NextMonth()As DateObject Set NextMonth =Me.MoveMonth(1)EndPropertyPublicPropertyGet EndOfMonth()As DateObject WithNew DateObject .Value=Me.FirstOfMonth.NextMonth.Value-1Set EndOfMonth =.Self EndWithEndProperty
以上で準備は完了。
使い方
※適当にサンプルを用意してみたので、標準モジュールに貼り付けて実行してみてください。
Sub hoge()Dim d As DateObject: Set d =New DateObject 'オブジェクト作成直後は、当日の日付が入る。 Debug.Print d.Value'日付をyyyymmdd形式で設定できる。 d.SetDateByYYYYMMDD "20171130"'普通に日付の代入もできる。 d.Value=Date'Date関数で今日の日付を作って代入'ToStringでフォーマット整形できる。 Debug.Print d.ToString("yyyymmdd")'月初の日付を取得する Debug.Print d.FirstOfMonth.Value'月末の日付をフォーマット指定で出力 Debug.Print d.EndOfMonth.ToString("ge年mm月dd日")'再来月末の日付をフォーマット指定で出力 Debug.Print d.NextMonth.NextMonth.EndOfMonth.ToString("yyyy-mm-dd")EndSub
結果は次のように出力される。
2017/11/30 20171130 2017/11/01 H29年11月30日 2018-01-31
このマクロを改造するのに必要な知識
例えばNextWeek命令が欲しいなど、改造したくなることがあるかもしれない。
その場合、まずはクラスモジュールの知識が必要になる。
以下に入門記事を書いているのでどうぞ。
thom.hateblo.jp
また、以下の記事のテクニックも使用しているのでご参考までに。
thom.hateblo.jp
thom.hateblo.jp
以上