0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

セルで指定されたファイルパスを読み取り印刷する方法

Last updated at Posted at 2020-05-30

TL;DR(3行)

  • セルで指定されたExcelファイルのパスを読み取り印刷できるようにする
  • 例では,3つのファイルパスを読み取って印刷ダイアログを表示させます
  • 印刷ダイアログを出さず連続で印刷する方法も紹介

前提条件

  • デスクトップにTestフォルダーがある

  • Testフォルダーの中にBookA.xlsx, Book1.xlsx, Book2.xlsx, Book3.xlsxが存在する
    1.PNG

  • Book1.xlsx~Book3.xlsxは何が書かれててもとりあえず良い

  • BookA.xlsxは,以下のようにBook1.xlsx~Book3.xlsxのファイルパスが記載されている
    キャプチャ.PNG

コード

BookAでVBEを開いて以下のコードを貼り付けて実行
A1~A3に書かれたパスのExcelファイルを印刷することができる


' メインプロシージャ
Sub Main()
  ' 変数の定義
  Dim filePath As String

  ' A1からA3のセルを参照
  For Each cell In Range("A1:A3")
    ' ファイルパスの取得
    filePath = cell.Value
    ' 印刷プロシージャの読み出し
    Call PrintBook(filePath)
  Next
End Sub


' 印刷用プロシージャ
Sub PrintBook(ByVal filePath As String, Optional ByVal sheetName As String = "")
  ' ブックを操作するために用意
  Dim wb As Workbook
  ' filePathで指定されたブックを開く
  Set wb = Workbooks.Open(Filename:=filePath, ReadOnly:=True)

  ' シート名が指定されていない場合,読み込んだブックから取得
  If sheetName <> "" Then
    wb.Sheets(sheetName).Select
  End If

  ' 印刷ダイアログを開く
  ' SendKeys "{ENTER}" '一気に印刷までしたい時はコメントを外す
  Application.Dialogs(xlDialogPrint).Show

  ' ファイルを閉じる
  wb.Close False
  ' wbの初期化
  Set wb = Nothing
End Sub

一気に印刷する場合

上記コードの当該コメントを外します

' 印刷ダイアログを開く
SendKeys "{ENTER}" '一気に印刷までしたい時はコメントを外す
Application.Dialogs(xlDialogPrint).Show

SendKeysでEnterを指定することで,
表示された印刷ダイアログにEnterキーが押された状態になり,すぐさま印刷が開始されます.

参考サイト

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?