LibreOffice Calc Basic - 印刷範囲を指定する方法

◆概要

 印刷範囲の設定には setPrintAreas メソッドを使用します。
構文
void setPrintAreas( [in] [].table.CellRangeAddress aPrintAreas )

このsetPrintArea メソッドの引数に使用する .table.CellRangeAddress で印刷する範囲を設定します。
Sheet シート
StartColumn 開始列
StartRow 開始行
EndColumn 終わりの列
EndRow 終わりの行

次の例は3番目のシートのセルA1からV38までを印刷範囲に指定しています。

Sub SetPrintArea_1
rem *********************************************************
rem Summary: 3番目のシートのセル範囲 A1:V38 を印刷範囲に設定
rem *********************************************************
    Dim oDoc As Object
    Dim oSheet As OBject
    Dim aRange As New com.sun.star.table.CellRangeAddress 
      
    oDoc = ThisComponent
    oSheet = oDoc.Sheets(2)
      With aRange
        .Sheet = 2      '3番目のシートを指定
        .StartColumn = 0'A列
        .StartRow = 0	'1行目
        .EndColumn = 21	'V列
        .EndRow = 37	'38行目
     End With

    oSheet.setPrintAreas(Array(aRange))
End Sub

◆印刷範囲を指定して印刷

 印刷範囲を指定して印刷するマクロです。
サンプルコードでは、印刷範囲としてA2:G22を指定し用紙の向きを横にして、A4用紙に印刷しています。
このマクロを実行する前に印刷したいシートをアクティブにしておく必要があります。

Sub PrintLandscape_setRange
    Dim oDoc as Object, oSheet as Object
    Dim oPrint_Range as Object
    Dim oPrint_Area(0)
    Dim arg(0) as new com.sun.star.beans.PropertyValue
    Dim PrinterProperties(1) as new com.sun.star.beans.PropertyValue
    oDoc = ThisComponent
    oSheet = oDoc.currentSelection.getSpreadsheet()
    oPrint_Range = oSheet.getCellRangeByName("A2:G22").rangeAddress
    oPrint_Area(0) = oPrint_Range
    oSheet.setPrintAreas(oPrint_Area())
    PrinterProperties(0).name="PaperOrientation"
    PrinterProperties(0).value=com.sun.star.view.PaperOrientation.LANDSCAPE
    PrinterProperties(1).name="PaperFormat"
    PrinterProperties(1).value=com.sun.star.view.PaperFormat.A4
    arg(0).name="Wait"
    arg(0).value=True
    oDoc.Printer = PrinterProperties()
    ThisComponent.print(arg())
End Sub

◆VBAを利用する

 ちょっと姑息な方法ですが、LibreOfficeのVBA互換機能を利用して印刷範囲を指定して印刷する方法があります。
VBA互換機能を使用するため、モジュールの先頭にOption VBASupport 1を記述する必要があります。

次の例では、menuシートにボタンを貼り付け、そのボタンにPrint_1を割り当てます。ボタンをクリックすると、別シートの「月次実績」という範囲名を選択してから印刷。その後、Mainシートに戻ります。
REM  *****  BASIC  *****
Option VBASupport 1

Sub Print_1
rem ******************************************
rem 範囲名「月次実績」を印刷する
rem ******************************************
    dim oDoc         As Object
    dim oSheet     As Object
    dim oSheets    As Object
    dim oController As Object
    dim ret%
    dim Buf             As Variant
    
    ret=MsgBox("プリントしますか? "& Chr$(13)  _
&"Do you want to continue?",4+32,"印刷の確認")
    If ret=6 then
        oDoc = thisComponent
        oController = oDoc.getCurrentController() 
        oSheets = oDoc.getSheets()

        Application.Goto Reference:="月次実績"
        Selection.PrintOut Copies:=1, Collate:=True
        rem Menuシートに戻る
        oController.setActiveSheet(oSheets.getByName("Main"))
           Application.Goto reference:=Range("A1"), Scroll:=True    
    End If        
End Sub
▼ページトップへ