Excel 2010でページ設定(PageSetup)の動作を高速化する

1年近く前につぶやいた話題ですが、今になっても取り扱っているサイトが少ないので今回記事を書いてみます。

Excel VBAでのページ設定(PageSetup)の動作が遅いことはよく知られたことで、これまでは高速化のためにExcel 4.0(XLM)マクロのPAGE.SETUP()が多くの場面で使われてきました。

Excel 2010では新たに「Application.PrintCommunication」プロパティが追加され、PageSetupプロパティを設定するコードの実行を高速化することができるようになりました。

実際にテストしたコードと結果は下記の通りです(テストしたブックは255シートで、1シートずつループで処理しています)。

Public Sub Test01()
'PrintCommunicationプロパティ無し
  Dim sht As Excel.Worksheet
  Dim t1 As Single, t2 As Single
  
  t1 = Timer
  For Each sht In ActiveWorkbook.Worksheets
    With sht.PageSetup
      .LeftMargin = Application.InchesToPoints(0.25)
      .RightMargin = Application.InchesToPoints(0.25)
      .TopMargin = Application.InchesToPoints(0.75)
      .BottomMargin = Application.InchesToPoints(0.75)
      .Orientation = xlLandscape
      .PaperSize = xlPaperLetter
      .FitToPagesWide = 1
      .FitToPagesTall = 1
    End With
  Next
  t2 = Timer
  MsgBox "Test01処理時間:" & t2 - t1 & "秒"
  Debug.Print t2 - t1
End Sub

Public Sub Test02()
'PrintCommunicationプロパティ有り
  Dim sht As Excel.Worksheet
  Dim t1 As Single, t2 As Single
  
  t1 = Timer
  Application.PrintCommunication = False
  For Each sht In ActiveWorkbook.Worksheets
    With sht.PageSetup
      .LeftMargin = Application.InchesToPoints(0.25)
      .RightMargin = Application.InchesToPoints(0.25)
      .TopMargin = Application.InchesToPoints(0.75)
      .BottomMargin = Application.InchesToPoints(0.75)
      .Orientation = xlLandscape
      .PaperSize = xlPaperLetter
      .FitToPagesWide = 1
      .FitToPagesTall = 1
    End With
  Next
  Application.PrintCommunication = True
  t2 = Timer
  MsgBox "Test02処理時間:" & t2 - t1 & "秒"
  Debug.Print t2 - t1
End Sub

上記結果を見ると確かにPrintCommunicationプロパティを設定した方が早く処理が終わっています。
下記Microsoftのページを見ると、Excel 4.0 マクロから新たに追加された機能への移行が推奨されているようです。

Excel 4.0 マクロを操作する
http://office.microsoft.com/ja-jp/excel-help/HA010336614.aspx
Migrating Excel 4 Macros to VBA
http://blogs.office.com/b/microsoft-excel/archive/2010/02/16/migrating-excel-4-macros-to-vba.aspx

Excel 2010を使用していて、PageSetupの遅さにお悩みの方は一度試してみてはいかがでしょうか?

コメントを残す