使用VBA在Excel中打印特定工作表,使用不同的打印区域和打印设置

时间:2015-10-06 20:19:03

标签: arrays vba excel-vba printing excel

我有一本包含6种不同工作表的工作簿。此工作簿需要为用户提供打印2组不同报告的选项。选项1将打印工作表1,3和5,选项2将打印工作表2,4和6.每个工作表将需要不同的打印范围和打印设置。我这样接近它并且想知道这是否是接近它的最佳方式(我确信有更好/更正确的方法)。

Sub printingSheets()

Dim Sh1 As Worksheet
Dim Sh3 As Worksheet
Dim Sh5 As Worksheet

With ThisWorkbook

Set Sh1 = .Sheets(“Dataset1”)
Set Sh3 = .Sheets(“Dataset2”)
Set Sh5 = .Sheets(“Dataset3”)

‘Setting the print area

Sh1.PageSetup.PrintArea = "$A$1:$C$5"
Sh3.PageSetup.PrintArea = "$A$1:$S$5"
Sh5.PageSetup.PrintArea = "$A$1:$AA$7"

‘Setting up the print setup

Sh1.PageSetup.PaperSize = xlPaperA4
Sh3.PageSetup.PaperSize = xlPaperA4
Sh5.PageSetup.PaperSize = xlPaperA3

‘Print

Array(Sh1, Sh3, Sh5).PrintOut Copies:=1

End Sub

然后我会为其他表格写一个单独的宏。

感谢愿意提供帮助的人!

1 个答案:

答案 0 :(得分:0)

我为每个功能制作单独的潜艇,并放置"魔法"顶部的数字,作为常数,以便于维护

Option Explicit

Private Const WS_NAME   As String = "Dataset"
Private Const WS_ID     As String = "1 2 3 4 5 6"           'Dataset & #
Private Const WS_RANGE1 As String = "A1 A1 A1 A1 A1 A1"     'First print Cell
Private Const WS_RANGE2 As String = "C5 X1 S5 X1 AA7 X1"    'Last print Cell
Private Const WS_SIZE   As String = "9 9 9 9 8 9"           'xlPaperA4=9, xlPaperA3=8

Public Sub printWSset()

    setPrintInfo        'main setup and config

    printSet "1 3 5"    'easy to change, independent of Worksheet setup

End Sub
Public Sub printSet(ByRef wsIDs As String)
    Dim wsID As Variant

    If Len(wsIDs) > 0 Then
        For Each wsID In Split(wsIDs)
            ThisWorkbook.Worksheets(wsID).PrintOut Copies:=1
        Next
    End If
End Sub

Public Sub setPrintInfo()
    Dim wsName As Variant, wsR1 As Variant, wsR2 As Variant, wsSz As Variant, i As Long

    wsName = Split(WS_ID)       'split string by default char (space); array base at 0
    wsR1 = Split(WS_RANGE1)
    wsR2 = Split(WS_RANGE2)
    wsSz = Split(WS_SIZE)

    For i = 0 To UBound(wsName)
        setInfo WS_NAME & wsName(i), wsR1(i), wsR2(i), Val(wsSz(i))
    Next
End Sub

Private Sub setInfo(ByVal x As String, r1 As Variant, r2 As Variant, sz As Long)

    With ActiveWorkbook.Worksheets(x).PageSetup
        .PrintArea = r1 & ":" & r2
        .PaperSize = sz
    End With

End Sub