■■■■■■■第4章 04■■■■■■■

■■■■p104プロンプト例

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

＃＃＃＃現在の状態
A3セル以下に、以下の形式でデータが縦に並んでいる 
　　・先頭の行は日付
　　・【】で囲まれているのは「区名」
　　・そのほかは「地域」で、後ろのかっこ内は枚数がある
　　・区や地域のそれぞれの表の行数はバラバラ
　　・日付が異なるデータは、空白行で区切られている

＃＃1日分のデータの例
2025/7/1
【浦和区】
岸町４丁目（50枚）
東高砂（250枚）
【緑区】
東浦和２丁目（300枚）
東浦和４丁目（200枚）
東浦和９丁目（200枚）

＃＃＃＃プログラムの実行結果
・「日付」「区名」「地域」「枚数」の項目を持つリストを作成
・結果は「整形後」シートに出力する
・マクロ名は「チラシ配布記録の整形」とする

＃＃結果の例 
日付	区名	地域	枚数
2025/7/1	浦和区	岸町４丁目	50
2025/7/1	緑区	東浦和２丁目	300
2025/7/1	緑区	東浦和４丁目	200
2025/7/1	緑区	東浦和９丁目	200


■■■■p105コード例

Sub チラシ配布記録の整形()
    Dim wsSrc As Worksheet, wsDest As Worksheet
    Dim lastRow As Long, i As Long
    Dim currentDate As String
    Dim currentKu As String
    Dim destRow As Long
    Dim lineText As String
    Dim region As String
    Dim sheetsExist As Boolean
    
    ' シート設定
    Set wsSrc = ThisWorkbook.Sheets(ActiveSheet.Name) '実行時のアクティブシート
    On Error Resume Next
    Set wsDest = ThisWorkbook.Sheets("整形後")
    If wsDest Is Nothing Then
        Set wsDest = ThisWorkbook.Sheets.Add(After:=wsSrc)
        wsDest.Name = "整形後"
    Else
        wsDest.Cells.Clear
    End If
    On Error GoTo 0
    
    ' ヘッダー設定
    wsDest.Range("A1").Value = "日付"
    wsDest.Range("B1").Value = "区名"
    wsDest.Range("C1").Value = "地域"
    wsDest.Range("D1").Value = "枚数"
    destRow = 2
    
    ' 元データ最終行取得
    lastRow = wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row
    
    For i = 3 To lastRow
        lineText = Trim(wsSrc.Cells(i, "A").Value)
        If lineText = "" Then
            ' 空行はスキップ（区切り）
            currentKu = ""
        ElseIf IsDate(lineText) Then
            ' 日付行
            currentDate = lineText
            currentKu = ""
        ElseIf Left(lineText, 1) = "【" And Right(lineText, 1) = "】" Then
            ' 区名行 【浦和区】
            currentKu = Mid(lineText, 2, Len(lineText) - 2)
        Else
            ' 地域（例：岸町４丁目（50枚））
            ' 地域名と枚数を分解
            Dim pos1 As Long, pos2 As Long
            pos1 = InStr(lineText, "（")
            pos2 = InStr(lineText, "枚）")
            If pos1 > 0 And pos2 > pos1 Then
                region = Left(lineText, pos1 - 1)
                Dim numberStr As String
                numberStr = Mid(lineText, pos1 + 1, pos2 - pos1 - 1)
                ' 枚数の数字だけ抜き出す（数字のみ）
                numberStr = Replace(numberStr, "枚", "")
                numberStr = Replace(numberStr, " ", "")
                ' 出力
                wsDest.Cells(destRow, "A").Value = currentDate
                wsDest.Cells(destRow, "B").Value = currentKu
                wsDest.Cells(destRow, "C").Value = region
                wsDest.Cells(destRow, "D").Value = Val(numberStr)
                destRow = destRow + 1
            End If
        End If
    Next i
    
    ' 列幅自動調整
    wsDest.Columns("A:D").AutoFit
    
    MsgBox "整形が完了しました。", vbInformation
End Sub

