【Excel VBA】沢山のシートがあり、印刷する一部のシートは除外したい場合

スポンサーリンク
この記事は約11分で読めます。

印刷に除外するワークシートの設定

前回の記事に以下のシートを印刷対象から除外します。

  • データ1
  • データ2
  • データ3

📌 追加された機能

「データ1」「データ2」「データ3の3つのシートを印刷対象から除外

excludeSheets の配列にシート名を登録し、該当するシートはスキップ

それ以外のシートのみ「手動印刷 or 自動印刷」の処理を実行

前回の記事に追加したコード

Sub PrintSheetsWithFukuokaShops()
    Dim ws As Worksheet          ' 各シートを処理するための変数
    Dim dataSheet As Worksheet   ' データシート(店番と店名があるシート)
    Dim fukuokaShops As Object   ' 福岡の店番を格納する辞書(重複回避)
    Dim cell As Range            ' セルを走査するための変数
    Dim password As String       ' シート保護解除用のパスワード
    Dim shopCode As Variant      ' 各シートの店番コード
    Dim printRange As Range      ' 印刷範囲
    Dim confirmPrint As VbMsgBoxResult ' ユーザーが選択する印刷方法
    Dim excludeSheets As Variant ' 除外するワークシートリスト
    Dim i As Integer

    ' ① ユーザーに印刷方法を選択させる
    confirmPrint = MsgBox("印刷を自動で行いますか?" & vbCrLf & "OK → 自動印刷 / キャンセル → プレビュー", vbOKCancel + vbQuestion, "印刷方法の選択")

    ' ② 除外するワークシートをリスト化
    excludeSheets = Array("データ1", "データ2", "データ3")

    ' ③ データシートの設定(店番コードと店名があるシート)
    Set dataSheet = ThisWorkbook.Sheets("データシート")

    ' ④ 福岡の店番を格納する辞書(重複を避けるために使用)
    Set fukuokaShops = CreateObject("Scripting.Dictionary")

    ' シート保護解除用のパスワード(不要なら "" に設定)
    password = "1234"

    ' ⑤ データシートのC列を走査し、「福岡」の店番を辞書に格納
    For Each cell In dataSheet.Range("C1:C" & dataSheet.Cells(Rows.Count, 3).End(xlUp).Row)
        If cell.Value = "福岡" And Not fukuokaShops.exists(cell.Offset(0, -2).Value) Then
            fukuokaShops.Add cell.Offset(0, -2).Value, True
        End If
    Next cell

    ' ⑥ 各シートをループして、該当するシートのみ印刷
    For Each ws In ThisWorkbook.Worksheets
        ' 除外リストに含まれるシートはスキップ
        For i = LBound(excludeSheets) To UBound(excludeSheets)
            If ws.Name = excludeSheets(i) Then GoTo NextSheet
        Next i

        ' ⑦ シート保護が有効なら解除
        If ws.ProtectContents Then
            On Error Resume Next
            ws.Unprotect Password:=password
            If Err.Number <> 0 Then
                MsgBox "シート '" & ws.Name & "' の保護を解除できませんでした。", vbCritical
                Exit Sub
            End If
            On Error GoTo 0
        End If

        ' ⑧ B2 または C4 に店番があるかチェック
        If Not IsEmpty(ws.Range("B2").Value) Then
            shopCode = ws.Range("B2").Value
            If fukuokaShops.exists(shopCode) Then
                ' A1:T60 を **書式①** で書式設定して印刷
                Set printRange = ws.Range("A1:T60")
                Call FormatAndPrintSheet_Type1(ws, printRange, confirmPrint)
            End If
        End If

        If Not IsEmpty(ws.Range("C4").Value) Then
            shopCode = ws.Range("C4").Value
            If fukuokaShops.exists(shopCode) Then
                ' A1:M46 を **書式②** で書式設定して印刷
                Set printRange = ws.Range("A1:M46")
                Call FormatAndPrintSheet_Type2(ws, printRange, confirmPrint)
            End If
        End If

NextSheet:
    Next ws

    ' 完了メッセージ
    MsgBox "福岡の店番があるシートの印刷が完了しました。", vbInformation
End Sub

' 【書式①】B2 に店番がある場合の書式設定と印刷
Sub FormatAndPrintSheet_Type1(ws As Worksheet, printRange As Range, confirmPrint As VbMsgBoxResult)
    With printRange
        .Font.Name = "Arial"
        .Font.Size = 12
        .Font.Bold = True
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .Interior.Color = RGB(200, 200, 255)
    End With

    With ws.PageSetup
        .PrintArea = printRange.Address
        .LeftMargin = Application.InchesToPoints(0.5)
        .RightMargin = Application.InchesToPoints(0.5)
        .TopMargin = Application.InchesToPoints(0.75)
        .BottomMargin = Application.InchesToPoints(0.75)
        .CenterHorizontally = True
        .CenterVertically = True
    End With

    ' 印刷方式の選択
    If confirmPrint = vbOK Then
        ws.PrintOut ' 自動印刷
    Else
        ws.PrintPreview ' プレビュー表示
    End If
End Sub

' 【書式②】C4 に店番がある場合の書式設定と印刷
Sub FormatAndPrintSheet_Type2(ws As Worksheet, printRange As Range, confirmPrint As VbMsgBoxResult)
    With printRange
        .Font.Name = "Calibri"
        .Font.Size = 10
        .Font.Italic = True
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlTop
        .Interior.Color = RGB(255, 255, 200)
    End With

    With ws.PageSetup
        .PrintArea = printRange.Address
        .LeftMargin = Application.InchesToPoints(0.3)
        .RightMargin = Application.InchesToPoints(0.3)
        .TopMargin = Application.InchesToPoints(0.5)
        .BottomMargin = Application.InchesToPoints(0.5)
        .CenterHorizontally = False
        .CenterVertically = False
    End With

    ' 印刷方式の選択
    If confirmPrint = vbOK Then
        ws.PrintOut ' 自動印刷
    Else
        ws.PrintPreview ' プレビュー表示
    End If
End Sub

 

📌 Dim i As Integer の使用箇所について

Dim i As Integer は、除外するワークシートのリストをループ処理するため に使用されています。
コード内では、excludeSheets(除外リスト)内のシート名と現在のシート名を比較し、一致する場合は印刷処理をスキップ するために使われています。

📍 Dim i As Integer の具体的な使用箇所

以下のコード部分で使用されています。

' ⑥ 各シートをループして、該当するシートのみ印刷
For Each ws In ThisWorkbook.Worksheets
    ' 除外リストに含まれるシートはスキップ
    For i = LBound(excludeSheets) To UBound(excludeSheets)
        If ws.Name = excludeSheets(i) Then GoTo NextSheet
    Next i

📌 どのように使われているのか?

  1. excludeSheets という配列(リスト)を作成
excludeSheets = Array("データ1", "データ2", "データ3")

For i = LBound(excludeSheets) To UBound(excludeSheets)

→このリストに含まれるシートは印刷対象から除外される

2.excludeSheets という配列(リスト)を作成

For i = LBound(excludeSheets) To UBound(excludeSheets)

→ 配列 excludeSheets の最初の要素 (LBound = 0) から最後の要素 (UBound = 4) までループする

3.現在の ws.Name(シート名)と excludeSheets(i)(除外リストのシート名)を比較

If ws.Name = excludeSheets(i) Then GoTo NextSheet

→ 現在のシートが「データ1」「データ2」「データ3」のどれかに一致する場合、印刷処理をスキップ

4.GoTo NextSheet により、次のシートに進む

NextSheet:
Next ws

→ 印刷処理を実行せず、次のシートへ進む

📌 まとめ

iexcludeSheets の配列の中身を 1 つずつチェックするために使われる

現在のシート (ws.Name) が excludeSheets(i) のどれかに該当すれば、印刷処理をスキップ

GoTo NextSheet で、そのシートの処理をスキップし、次のシートへ移動

コメント

タイトルとURLをコピーしました