■■■■■■■第3章 08■■■■■■■

■■■■p102プロンプト例

あなたは優秀なExcel VBAのプログラマーです。
次の操作をするExcel VBAのプログラムを書いてください。

・指定した年と月のカレンダーを作る
・最初にダイアログボックスを表示して、年を指定する
・次にダイアログボックスを表示して、月を指定する
・カレンダーは日曜で始まり、土曜で終わる
・日曜は赤色、土曜は青色で表示する
・マクロ名は「カレンダー作成」とする


■■■■p102コード例

Sub カレンダー作成()
    Dim y As Integer, m As Integer
    Dim firstDay As Date, lastDay As Date
    Dim startCol As Integer, startRow As Integer
    Dim i As Integer, d As Integer
    Dim ws As Worksheet
    
    ' 年の入力
    y = InputBox("年を入力してください（例：2025）", "年の指定")
    If y < 1 Then Exit Sub
    
    ' 月の入力
    m = InputBox("月を入力してください（1～12）", "月の指定")
    If m < 1 Or m > 12 Then Exit Sub
    
    ' 新しいシートを作成
    Set ws = Sheets.Add
    ws.Name = y & "年" & m & "月"
    
    ' カレンダーの開始位置
    startRow = 3
    startCol = 2
    
    ' 曜日見出し
    Dim daysOfWeek As Variant
    daysOfWeek = Array("日", "月", "火", "水", "木", "金", "土")
    For i = 0 To 6
        ws.Cells(startRow, startCol + i).Value = daysOfWeek(i)
        ws.Cells(startRow, startCol + i).Font.Bold = True
        ws.Cells(startRow, startCol + i).HorizontalAlignment = xlCenter
    Next i
    
    ' 1日と月末日
    firstDay = DateSerial(y, m, 1)
    lastDay = DateSerial(y, m + 1, 0)
    
    ' 最初の行の開始曜日
    Dim dayOfWeek As Integer
    dayOfWeek = Weekday(firstDay, vbSunday) - 1 ' 0=日曜, 6=土曜
    
    ' 日付を入力
    d = 1
    Dim rowOffset As Integer, colOffset As Integer
    rowOffset = 1
    
    Do While d <= Day(lastDay)
        For colOffset = 0 To 6
            If (rowOffset = 1 And colOffset < dayOfWeek) Then
                ' 空白セル
            ElseIf d <= Day(lastDay) Then
                ws.Cells(startRow + rowOffset, startCol + colOffset).Value = d
                ws.Cells(startRow + rowOffset, startCol + colOffset).HorizontalAlignment = xlCenter
                ' 日曜=赤、土曜=青
                If colOffset = 0 Then
                    ws.Cells(startRow + rowOffset, startCol + colOffset).Font.Color = vbRed
                ElseIf colOffset = 6 Then
                    ws.Cells(startRow + rowOffset, startCol + colOffset).Font.Color = vbBlue
                End If
                d = d + 1
            End If
        Next colOffset
        rowOffset = rowOffset + 1
    Loop
    
    ' 罫線を引く
    Dim lastRow As Long, lastCol As Long
    lastRow = startRow + rowOffset - 1
    lastCol = startCol + 6
    ws.Range(ws.Cells(startRow, startCol), ws.Cells(lastRow, lastCol)).Borders.LineStyle = xlContinuous
    
    ' タイトル
    ws.Range(ws.Cells(1, startCol), ws.Cells(1, startCol + 6)).Merge
    ws.Cells(1, startCol).Value = y & "年 " & m & "月"
    ws.Cells(1, startCol).HorizontalAlignment = xlCenter
    ws.Cells(1, startCol).Font.Size = 16
    ws.Cells(1, startCol).Font.Bold = True
    
    MsgBox "カレンダーを作成しました！", vbInformation
End Sub


■■■■p104プロンプト例

以下の改良を加えてください。

・カレンダーのサイズを大きくする
・各日付のセルには、メモを書き込めるように余白を設ける
・曜日の見出し行は薄い灰色で塗りつぶす
・日曜のセルはピンク、土曜のセルは水色に塗りつぶす
・カレンダーの上部に「○年○月」と大きく表示する


■■■■p104コード例

Sub カレンダー作成()
    Dim y As Integer, m As Integer
    Dim firstDay As Date
    Dim startCol As Integer, startRow As Integer
    Dim i As Integer, d As Integer
    Dim ws As Worksheet
    
    ' 年を取得
    y = InputBox("カレンダーの年を入力してください（例: 2025）", "年の指定")
    If y < 1900 Or y > 9999 Then
        MsgBox "年の値が不正です。", vbExclamation
        Exit Sub
    End If
    
    ' 月を取得
    m = InputBox("カレンダーの月を入力してください（1～12）", "月の指定")
    If m < 1 Or m > 12 Then
        MsgBox "月の値が不正です。", vbExclamation
        Exit Sub
    End If
    
    ' 新しいシート作成
    Set ws = Worksheets.Add
    ws.Name = y & "年" & m & "月カレンダー"
    
    ' カレンダーの開始位置
    startRow = 4 ' 見出し用に上部空ける
    startCol = 1
    
    ' タイトル表示（例: 2025年8月）
    ws.Range(ws.Cells(1, startCol), ws.Cells(1, startCol + 6)).Merge
    ws.Cells(1, startCol).Value = y & "年" & m & "月"
    ws.Cells(1, startCol).Font.Size = 20
    ws.Cells(1, startCol).Font.Bold = True
    ws.Cells(1, startCol).HorizontalAlignment = xlCenter
    
    ' 曜日ヘッダー作成
    Dim daysOfWeek As Variant
    daysOfWeek = Array("日", "月", "火", "水", "木", "金", "土")
    
    For i = 0 To 6
        ws.Cells(startRow, startCol + i).Value = daysOfWeek(i)
        ws.Cells(startRow, startCol + i).HorizontalAlignment = xlCenter
        ws.Cells(startRow, startCol + i).Font.Bold = True
        ws.Cells(startRow, startCol + i).Interior.Color = RGB(220, 220, 220) ' 薄い灰色
        
        ' 日曜赤文字、土曜青文字
        If i = 0 Then
            ws.Cells(startRow, startCol + i).Font.Color = RGB(255, 0, 0)
        ElseIf i = 6 Then
            ws.Cells(startRow, startCol + i).Font.Color = RGB(0, 0, 255)
        End If
    Next i
    
    ' 月初の日付と曜日を取得
    firstDay = DateSerial(y, m, 1)
    Dim firstWeekDay As Integer
    firstWeekDay = Weekday(firstDay, vbSunday) - 1 ' 0=日曜
    
    ' 日付配置
    d = 1
    Dim lastDay As Integer
    lastDay = Day(DateSerial(y, m + 1, 0))
    
    Dim rowNum As Integer, colNum As Integer
    rowNum = startRow + 1
    colNum = startCol + firstWeekDay
    
    Do While d <= lastDay
        ws.Cells(rowNum, colNum).Value = d
        ws.Cells(rowNum, colNum).HorizontalAlignment = xlLeft
        ws.Cells(rowNum, colNum).VerticalAlignment = xlTop
        ws.Cells(rowNum, colNum).Font.Size = 12
        ws.Cells(rowNum, colNum).Font.Bold = True
        
        ' 日曜背景＝ピンク、土曜背景＝水色
        If colNum = startCol Then
            ws.Cells(rowNum, colNum).Font.Color = RGB(255, 0, 0)
            ws.Cells(rowNum, colNum).Interior.Color = RGB(255, 200, 200)
        ElseIf colNum = startCol + 6 Then
            ws.Cells(rowNum, colNum).Font.Color = RGB(0, 0, 255)
            ws.Cells(rowNum, colNum).Interior.Color = RGB(200, 230, 255)
        End If
        
        ' 次の日
        d = d + 1
        colNum = colNum + 1
        If colNum > startCol + 6 Then
            colNum = startCol
            rowNum = rowNum + 1
        End If
    Loop
    
    ' 罫線・セルサイズ調整（大きめ）
    With ws.Range(ws.Cells(startRow, startCol), ws.Cells(rowNum, startCol + 6))
        .Borders.LineStyle = xlContinuous
        .ColumnWidth = 15
        .RowHeight = 60
    End With
    
    MsgBox y & "年" & m & "月のカレンダーを作成しました。", vbInformation
End Sub


■■■■p105プロンプト例

・日本の祝日を赤色で表示し、祝日の名称もセルに表示する


■■■■p106コード例

Sub カレンダー作成()
    Dim y As Integer, m As Integer
    Dim firstDay As Date, lastDay As Integer
    Dim startCol As Integer, startRow As Integer
    Dim ws As Worksheet, holWs As Worksheet
    Dim holidayDic As Object
    Dim i As Integer, d As Integer, rowNum As Integer, colNum As Integer
    
    '─ 年・月の入力 ─
    y = InputBox("カレンダーの年を入力してください（例: 2025）", "年の指定")
    If y < 1900 Or y > 9999 Then MsgBox "年の値が不正です。", vbExclamation: Exit Sub
    m = InputBox("カレンダーの月を入力してください（1～12）", "月の指定")
    If m < 1 Or m > 12 Then MsgBox "月の値が不正です。", vbExclamation: Exit Sub
    
    '─ 新規シートの設定 ─
    Set ws = Worksheets.Add
    ws.Name = y & "年" & m & "月カレンダー"
    
    '─ 祝日データ取得シート ─
    On Error Resume Next
    Set holWs = Worksheets("祝日一覧")
    On Error GoTo 0
    If holWs Is Nothing Then
        Set holWs = Worksheets.Add
        holWs.Name = "祝日一覧"
        Call ImportHolidaysByJSON(holWs)
    End If
    
    '─ Dictionary に祝日を格納 ─
    Set holidayDic = CreateObject("Scripting.Dictionary")
    Dim lr As Long
    lr = holWs.Cells(Rows.Count, 1).End(xlUp).Row
    For i = 2 To lr
        holidayDic(CDate(holWs.Cells(i, 1).Value)) = holWs.Cells(i, 2).Value
    Next i
    
    '─ 表示位置とタイトル ─
    startRow = 4: startCol = 1
    With ws.Range(ws.Cells(1, startCol), ws.Cells(1, startCol + 6))
        .Merge
        .Value = y & "年" & m & "月"
        .Font.Size = 20: .Font.Bold = True
        .HorizontalAlignment = xlCenter
    End With
    
    '─ 曜日見出し ─
    Dim daysOfWeek As Variant: daysOfWeek = Array("日", "月", "火", "水", "木", "金", "土")
    For i = 0 To 6
        With ws.Cells(startRow, startCol + i)
            .Value = daysOfWeek(i)
            .HorizontalAlignment = xlCenter
            .Font.Bold = True
            .Interior.Color = RGB(220, 220, 220)
            If i = 0 Then .Font.Color = RGB(255, 0, 0)
            If i = 6 Then .Font.Color = RGB(0, 0, 255)
        End With
    Next i
    
    '─ 日付配置・祝日判定 ─
    firstDay = DateSerial(y, m, 1)
    lastDay = Day(DateSerial(y, m + 1, 0))
    rowNum = startRow + 1
    colNum = startCol + (Weekday(firstDay, vbSunday) - 1)
    
    For d = 1 To lastDay
        Dim dt As Date: dt = DateSerial(y, m, d)
        With ws.Cells(rowNum, colNum)
            .Value = d
            .HorizontalAlignment = xlLeft
            .VerticalAlignment = xlTop
            .Font.Size = 12: .Font.Bold = True
            ' 背景と文字色
            If Weekday(dt) = vbSunday Then
                .Font.Color = RGB(255, 0, 0)
                .Interior.Color = RGB(255, 200, 200)
            ElseIf Weekday(dt) = vbSaturday Then
                .Font.Color = RGB(0, 0, 255)
                .Interior.Color = RGB(200, 230, 255)
            End If
            ' 祝日判定
            If holidayDic.Exists(dt) Then
                .Font.Color = RGB(255, 0, 0)
                .Interior.Color = RGB(255, 150, 150)
                .Value = d & Chr(10) & holidayDic(dt)
                .WrapText = True
            End If
        End With
        colNum = colNum + 1
        If colNum > startCol + 6 Then colNum = startCol: rowNum = rowNum + 1
    Next d
    
    '─ 罫線とサイズ調整 ─
    With ws.Range(ws.Cells(startRow, startCol), ws.Cells(rowNum, startCol + 6))
        .Borders.LineStyle = xlContinuous
        .ColumnWidth = 15
        .RowHeight = 60
    End With
    
    MsgBox y & "年" & m & "月のカレンダーを作成しました。", vbInformation
End Sub

'─ JSONから祝日一覧取得 sub ─
Sub ImportHolidaysByJSON(targetWs As Worksheet)
    Dim http As Object, resp As String
    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open "GET", "https://holidays-jp.github.io/api/v1/date.json", False
    http.send
    If http.Status <> 200 Then MsgBox "祝日一覧取得失敗", vbExclamation: Exit Sub
    
    Dim json As String: json = Mid(http.responseText, 2, Len(http.responseText) - 2)
    Dim entries As Variant: entries = Split(json, ",")
    
    targetWs.Cells(1, 1).Value = "日付"
    targetWs.Cells(1, 2).Value = "祝日名"
    Dim i As Long, kv As Variant
    For i = 0 To UBound(entries)
        kv = Split(entries(i), ":")
        Dim dayStr As String, nameStr As String
        dayStr = Replace(Replace(Replace(kv(0), """", ""), " ", ""), vbLf, "")
        nameStr = Replace(Replace(Replace(kv(1), """", ""), " ", ""), vbLf, "")
        dayStr = Replace(dayStr, "-", "/")
        targetWs.Cells(i + 2, 1).Value = CDate(dayStr)
        targetWs.Cells(i + 2, 2).Value = nameStr
    Next i
    targetWs.Columns("A:B").AutoFit
End Sub
