📊 Excel VBA Top100
🔧

CalculateWorkdays

ユーティリティ

開始日から終了日までの営業日数を計算する

🎬 デモGIF準備中

📖 使い方

  1. VBAエディタを開く(Alt + F11)
  2. モジュールを挿入(挿入 > モジュール)
  3. 下記VBAコードをコピー&ペースト
  4. ブック上で実行(Alt + F8 でマクロ選択)
💡 実行例: 実行すると開始日・終了日を入力して営業日数が計算される

💻 VBAコード

' CalculateWorkdays
' -----------------
' Macro Name: CalculateWorkdays
' Description: 開始日から終了日までの営業日数を計算する
' Parameters: なし
' Returns: なし
' Usage: 実行すると開始日・終了日を入力して営業日数が計算される
' -----------------

Sub CalculateWorkdays()
    Dim startDate As Date
    Dim endDate As Date
    Dim workdays As Long
    Dim ws As Worksheet
    Dim outputCell As String

    On Error GoTo ErrorHandler

    Dim startDateStr As String
    startDateStr = InputBox("開始日を入力 (yyyy/mm/dd):", "営業日計算", Format(Date, "yyyy/mm/dd"))

    If startDateStr = "" Then
        Exit Sub
    End If

    On Error Resume Next
    startDate = CDate(startDateStr)
    On Error GoTo ErrorHandler
    If Err.Number <> 0 Then
        MsgBox "日付の形式が正しくありません。", vbExclamation
        Exit Sub
    End If

    Dim endDateStr As String
    endDateStr = InputBox("終了日を入力 (yyyy/mm/dd):", "営業日計算", Format(Date, "yyyy/mm/dd"))

    If endDateStr = "" Then
        Exit Sub
    End If

    On Error Resume Next
    endDate = CDate(endDateStr)
    On Error GoTo ErrorHandler
    If Err.Number <> 0 Then
        MsgBox "日付の形式が正しくありません。", vbExclamation
        Exit Sub
    End If

    If endDate < startDate Then
        MsgBox "終了日が開始日보다前です。", vbExclamation
        Exit Sub
    End If

    workdays = Application.WorksheetFunction.NetworkDays(startDate, endDate)

    Set ws = ActiveSheet
    outputCell = InputBox("結果を出力するセルアドレスを入力:", "営業日計算", "A1")

    If outputCell <> "" Then
        ws.Range(outputCell).Value = workdays
        ws.Range(outputCell).NumberFormat = "0"
    End If

    MsgBox startDate & " から " & endDate & " まで:" & vbCrLf & _
           "営業日数: " & workdays & " 日", vbInformation
    Exit Sub

ErrorHandler:
    MsgBox "エラーが発生しました: " & Err.Description, vbCritical
End Sub