■■■■■■■第3章 02■■■■■■■

■■■■p67プロンプト例

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

・選択したセル範囲の各行の下に、1行ずつ空白行を挿入する
・マクロ名は「空白行挿入」とする 


■■■■p67コード例

Sub 空白行挿入()
    Dim rng As Range
    Dim i As Long
    Dim startRow As Long
    Dim endRow As Long

    ' セル範囲が選択されているか確認
    If TypeName(Selection) <> "Range" Then
        MsgBox "セル範囲を選択してください。", vbExclamation
        Exit Sub
    End If

    Set rng = Selection

    ' 選択範囲の最初と最後の行番号を取得
    startRow = rng.Rows(1).Row
    endRow = rng.Rows(rng.Rows.Count).Row

    ' 下から上に向かって処理（行番号がずれないように）
    For i = endRow To startRow Step -1
        Rows(i + 1).Insert Shift:=xlDown
    Next i
End Sub


■■■■p69プロンプト例

一番下に追加した行に、罫線が付きませんでした。
実行後は、表の左上隅のセルを選択してください。


■■■■p69コード例

Sub 空白行挿入()
    Dim rng As Range
    Dim i As Long
    Dim startRow As Long
    Dim endRow As Long
    Dim colCount As Long

    ' セル範囲が選択されているか確認
    If TypeName(Selection) <> "Range" Then
        MsgBox "セル範囲を選択してください。", vbExclamation
        Exit Sub
    End If

    Set rng = Selection

    ' 選択範囲の行・列情報を取得
    startRow = rng.Rows(1).Row
    endRow = rng.Rows(rng.Rows.Count).Row
    colCount = rng.Columns.Count

    ' 下から上に処理して、各行の下に空白行を挿入＆書式コピー
    For i = endRow To startRow Step -1
        ' 挿入する行の位置
        Rows(i + 1).Insert Shift:=xlDown
        ' 書式を上の行からコピー
        Range(Cells(i, rng.Column), Cells(i, rng.Column + colCount - 1)).Copy
        Range(Cells(i + 1, rng.Column), Cells(i + 1, rng.Column + colCount - 1)).PasteSpecial Paste:=xlPasteFormats
    Next i

    ' コピーの選択解除
    Application.CutCopyMode = False

    ' 表の左上セルを選択
    Cells(startRow, rng.Column).Select
End Sub


■■■■p70プロンプト例

・挿入した空白行の行見出しとして「前年比」と入力する


■■■■p70コード例（「前年比」と自動入力）

Sub 空白行挿入()
    Dim rng As Range
    Dim i As Long
    Dim startRow As Long
    Dim endRow As Long
    Dim colCount As Long
    Dim insertRow As Long
    Dim startCol As Long

    ' セル範囲が選択されているか確認
    If TypeName(Selection) <> "Range" Then
        MsgBox "セル範囲を選択してください。", vbExclamation
        Exit Sub
    End If

    Set rng = Selection

    ' 範囲の行・列の情報を取得
    startRow = rng.Rows(1).Row
    endRow = rng.Rows(rng.Rows.Count).Row
    colCount = rng.Columns.Count
    startCol = rng.Columns(1).Column

    ' 下から上に処理（行の挿入で位置がずれないように）
    For i = endRow To startRow Step -1
        insertRow = i + 1
        ' 行を挿入
        Rows(insertRow).Insert Shift:=xlDown

        ' 書式コピー
        Range(Cells(i, startCol), Cells(i, startCol + colCount - 1)).Copy
        Range(Cells(insertRow, startCol), Cells(insertRow, startCol + colCount - 1)).PasteSpecial Paste:=xlPasteFormats

        ' 挿入行の1列目に「前年比」と入力
        Cells(insertRow, startCol).Value = "前年比"
    Next i

    ' コピー選択解除
    Application.CutCopyMode = False

    ' 表の左上セルを選択
    Cells(startRow, startCol).Select
End Sub
