如何循环将多个页面打印为一个pdf

时间:2019-06-23 19:13:14

标签: excel vba

我正在尝试创建用于打印日常计划程序的宏。每天一页。我已经创建了某种模板,现在,每次代码运行周期时,它都会更改日期和星期数等,然后打印页面。但是,像这样的每个页面都在不同的pdf文件中。有什么办法,如何每次将新页面添加到相同的pdf(范围相同,但数据不同)然后打印?

For i = 1 To 365

ActiveSheet.PrintOut

Range("A26") = WorksheetFunction.RoundUp((i + 2) / 7, 0) & ". week" 'week number

Range("A1").Value = Range("A1").Value + 1  'change date

Range("A1").Select
If (i Mod 2 = 0) Then
    Selection.HorizontalAlignment = xlLeft 'left page
Else
    Selection.HorizontalAlignment = xlRight 'right page
End If

Next i

1 个答案:

答案 0 :(得分:0)

我已经修改了您的宏,以便它首先创建一个新的临时工作簿,在其中复制每个更新的工作表。然后,它使用ExportAsFixedFormat方法将工作簿打印到指定的PDF文件(相应地更改文件名)。然后,它删除临时工作簿。请注意,在代码的开头,将ScreenUpdating设置为False,以便所有这些操作都在后台进行。另外,假设模板工作表是活动工作表。

Option Explicit

Sub PrintDailyPlanner()

    Dim sourceWS As Worksheet
    Dim tempWB As Workbook
    Dim i As Long

    Application.ScreenUpdating = False

    'set the active sheet
    Set sourceWS = ActiveSheet

    'create a new temporary workbook with one worksheet
    Set tempWB = Workbooks.Add(Template:=xlWBATWorksheet)

    'copy the source worksheet each time it's updated to the newly created temporary workbook
    With sourceWS
        For i = 1 To 365

            .Range("A26") = WorksheetFunction.RoundUp((i + 2) / 7, 0) & ". week" 'week number

            .Range("A1").Value = .Range("A1").Value + 1  'change date

            If (i Mod 2 = 0) Then
                .Range("A1").HorizontalAlignment = xlLeft 'left page
            Else
                .Range("A1").HorizontalAlignment = xlRight 'right page
            End If

            .Copy after:=tempWB.Worksheets(tempWB.Worksheets.Count)

        Next i
    End With

    'delete the first worksheet from the temporary workbook
    Application.DisplayAlerts = False
    tempWB.Worksheets(1).Delete
    Application.DisplayAlerts = True

    'print the temporary workbook to PDF file (change the filename accordingly)
    tempWB.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Users\Domenic\Desktop\sample.pdf"

    'close the temporary workbook, without saving
    tempWB.Close SaveChanges:=False

    Application.ScreenUpdating = True

End Sub

希望这会有所帮助!