Excel VBAで先月の日付を取得する|DateAdd・Format・Year・Month関数使用

今月の1日からDateAdd関数で先月の1日を取得し、そこから末日を求めます。



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

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

■ VBAで先月の日付を取得する方法

  1. 本日の「年」を、Year関数で取得します。
  2. 本日の「月」を、Month関数で取得します。
  3. Format関数で今月の1日を取得します。
  4. DateAdd関数で、一月減算し先月の1日の日付を取得します。
  5. 先月の1日から末日を取得します。
    取得方法: 28日から1日ずつ加算し、日が1日になる1日前が末日になります。
  6. 結果をセルに代入し完了です。

関連する「今月の日付を取得する|月の末日を取得するコード」も参照してください。




Excel実行画面

シートにコマンドボタンと日付の表示セルを配置しています。
「先月の日付」ボタンをクリックすると、開始日と終了日が表示されます。

先月の日付を計算し結果を表示するシート



Excel VBA実行コード

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 tdate As Date
    Dim tsdate As Date
    Dim tedate As Date
    
    ly = Year(Date)
    lm = Month(Date)
    
    '今月の開始日
    tdate = Format(ly & "/" & lm & "/1", "yyyy/mm/dd")
    '先月の1日
    tsdate = DateAdd("m", -1, tdate)
    Range("C6") = tsdate
    
    ly = Year(tsdate)
    lm = Month(tsdate)
    ld = MonthLastDay(ly, lm)
    
    '先月の終了日
    tedate = Format(ly & "/" & lm & "/" & ld, "yyyy/mm/dd")
    Range("C7") = tedate
    
End Sub




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

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


Copyright (c) Excel-Excel ! All rights reserved