先週1週間の日付を取得

先週1週間の日付を計算します。
報告書ファイルを作成する際の手間を削減できます。
本日が2024年1月8日の場合、先週一週間は、2023年12月31日~2024年1月6日となります。
引数を開始日、基準曜日を変更することができます。

Sub sample1()
	MsgBox GetOneWeekBefore()
End Sub

' 先週の一週間の日付を取得
Function GetOneWeekBefore(Optional ByVal strDate As String = "", _
			Optional ByVal stweekday As Integer = vbSunday) As String
	Dim baseday As Date	' 基準日
	Dim stdate As Date	' 先週の開始日
	Dim endate As Date	' 先週の終了日
	Dim nWeek As Integer	' 曜日

	' 範囲外の場合は、日曜日を開始とする
	If stweekday < vbSunday Or stweekday > vbSaturday Then
		stweekday = vbSunday	' 日曜日(1)を設定
	End If

	' 日付の指定が無ければ本日を基準日にする
	If strDate = "" Then
		baseday = Date		' 基準日は本日を取得
	Else
		baseday = strDate	' 基準日を設定
	End If

	nWeek = Weekday(baseday)	' 曜日を取得する

	' 先週の開始日と終了日を計算
	If nWeek < stweekday Then
		stdate = baseday - nWeek - 6 + stweekday - 8
		endate = baseday - nWeek + stweekday - 8
	Else
		stdate = baseday - nWeek - 6 + stweekday - 1
		endate = baseday - nWeek + stweekday - 1
	End If

	' 結果を戻す
	GetOneWeekBefore = (Format(stdate, "yyyymmdd")) & "-" _
			 & (Format(endate, "yyyymmdd"))
End Function

コメント