Excelで家計簿ソフトを作ってみよう

Step 9 今月の日付と先月の日付を取得する

集計用のユーザーフォームで、「先月」と「今月」ボタンをクリックした場合の、1日~月の末日までの日付を取得します。

基準日は本日の日付になります。


Homeに戻る > Excelでアプリケーションソフト2 > 家計簿ソフト

実行画面

集計ユーザーフォーム
日付を指定し集計するフォーム


先月の日付を取得した結果
2009年6月28日の先月ですので、2009/05/01 ~ 2009/05/31 になっています。
先月の日付のイミディエイトウィンドウ

今月の日付を取得した結果
2009年6月28日の今月ですので、2009/06/01 ~ 2009/06/30 になっています。
今月の日付のイミディエイトウィンドウ


実行VBAコード

'月の末日を取得
Private 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 ExGetThisMonth(ByRef stdate As Date, endate As Date)
    Dim ly As Integer
    Dim lm As Integer
    Dim ld As Integer
    
    ly = Year(Date)
    lm = Month(Date)
    ld = MonthLastDay(ly, lm)
    
    '開始日
    stdate = Format(ly & "/" & lm & "/1", "yyyy/mm/dd")
        
    '終了日
    endate = Format(ly & "/" & lm & "/" & ld, "yyyy/mm/dd")
    
End Sub

'先月の日付
Private Sub ExGetAgoMonth(ByRef stdate As Date, endate As Date)
    Dim ly As Integer
    Dim lm As Integer
    Dim ld As Integer
    Dim tdate As Date
    
    ly = Year(Date)
    lm = Month(Date)
    
    '今月の開始日
    tdate = Format(ly & "/" & lm & "/1", "yyyy/mm/dd")
    '先月の1日
    stdate = DateAdd("m", -1, tdate)
        
    ly = Year(stdate)
    lm = Month(stdate)
    ld = MonthLastDay(ly, lm)
    
    '先月の終了日
    endate = Format(ly & "/" & lm & "/" & ld, "yyyy/mm/dd")
    
End Sub

'先月ボタン
Private Sub CommandButton4_Click()
    Dim stdt As Date
    Dim endt As Date
    
    ExGetAgoMonth stdt, endt

    Debug.Print stdt & "  ~  " & endt
End Sub

'今月ボタン
Private Sub CommandButton5_Click()
    Dim stdt As Date
    Dim endt As Date
    
    ExGetThisMonth stdt, endt

    Debug.Print stdt & "  ~  " & endt
End Sub



Homeに戻る > Excelでアプリケーションソフト2 > 家計簿ソフト

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


Copyright (c) Excel-Excel ! All rights reserved