Excel VBAで今月の日付を取得する|月の末日を取得するコード

Year関数・Month関数・Do Loopなどを使用し月の末日を取得します。



Homeに戻る > Excel 日付・時間のTipsへ

今月の日付とは、1日~今月末の日付です。

■ 取得方法

  1. 本日の「年」を、Year関数で取得します。
  2. 本日の「月」を、Month関数で取得します。
  3. 本日の月の末日を取得します。
      取得方法: 28日から1日ずつ加算し、日が1日になる1日前が末日になります。
  4. 取得した「年」「月」「1」で開始日になります。
  5. 取得した「年」「月」「末日」で終了日になります。

関連する「Excel VBAで先月の日付を取得する|DateAdd・Format・Year・Month関数使用」も参照してください。



Excel実行画面

シートにコマンドボタンと、開始日と終了日の表示セルを配置しています。

「今月の日付」ボタンをクリックすると、開始日と終了日が表示されます。

開始日と終了日を取得し、セルに表示するシート


Excel VBA実行コード

コマンドボタンをクリックするとイベントが発生し、MonthLastDayプロシージャを呼び出します。
MonthLastDayプロシージャは年・月を引数にしています。
Do Loopで28日から翌月の1日になるまでループし、その前日が月の末日になります。

Option Explicit

'月の末日を取得し返す
Public Function MonthLastDay(yy As Integer, mm As Integer) As Integer
    Dim i As Integer
    Dim tdate As Date
    
    tdate = Format(yy & "/" & mm & "/1", "yyyy/mm/dd")
    i = 28
    Do
        i = i + 1
    Loop Until Day(tdate + i - 1) = 1
    MonthLastDay = i - 1
End Function

Private Sub CommandButton1_Click()
    Dim ly As Integer
    Dim lm As Integer
    Dim ld As Integer
    Dim tsdate As Date
    Dim tedate As Date
    
    ly = Year(Date)
    lm = Month(Date)
    ld = MonthLastDay(ly, lm)
    
    '開始日
    tsdate = Format(ly & "/" & lm & "/1", "yyyy/mm/dd")
    Range("C6") = tsdate
    
    '終了日
    tedate = Format(ly & "/" & lm & "/" & ld, "yyyy/mm/dd")
    Range("C7") = tedate
    
End Sub




Homeに戻る > Excel 日付・時間のTipsへ

■■■
このサイトの内容を利用して発生した、いかなる問題にも一切責任は負いませんのでご了承下さい
■■■
当ホームページに掲載されているあらゆる内容の無許可転載・転用を禁止します


Copyright (c) Excel-Excel ! All rights reserved