excel 在同一PDF页面中打印两张表单

wrrgggsh  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(219)

我目前正在使用下面的代码将两个表格导出到PDF中。两个表格的打印区域都在表格中预先标记好了,所以导出效果很好。但是,在PDF中,第一个表格被打印到第一页,第二个表格被打印到第二页。这有时会在第一页留下很多空白,因为表格1只有几行。
在vba中,是否可以从PDF第一页中第一个表格/表单的打印区域结束处开始第二个表格(位于第二个表单中)?我不能在同一个表单中有两个表格。

Dim fname As String, fpath As String, srcFile As String
fpath = "C:\"
fname = "export.pdf"
srcFile = ThisWorkbook.Name
ThisWorkbook.Sheets(Array(Sheet1.Name, Sheet2.Name)).Select

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fpath & fname, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
to94eoyn

to94eoyn1#

这种保存方式必须在Excel PageSetup设置中处理,但它确实提供了这种可能性仅每张工作表。因此,您应该使用一个技巧,将讨论中的两个表复制到一个临时工作表中,将PageSetup.FitToPagesTallFitToPagesWide设置为1,发布新创建的工作表,并在最后删除它:

Sub exportTwoSheetsInOne()
 Dim fname As String, fpath As String, wb As Workbook, sh As Worksheet
 Dim tblSh1 As ListObject, tblSh2 As ListObject, lastR As Long

 Set wb = ThisWorkbook
 fpath = wb.Path & "\":  fname = "export.pdf" 'you can use a different path if user permissions permit that location

 Set tblSh1 = wb.Worksheets("Sheet1").ListObjects(1)
 Set tblSh2 = wb.Worksheets("Sheet2").ListObjects(1)

 Set sh = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.count))
 tblSh1.Range.Copy sh.Range("A1")

 lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'calculate the place where the second table to be copied
 tblSh2.Range.Copy sh.Range("A" & lastR + 2)
 
If Dir(fpath & fname) <> "" Then Kill fpath & fname

Application.ScreenUpdating = False: Application.Calculation = xlCalculationManual 'some optimization
    With sh
       With .PageSetup
           .FitToPagesTall = 1
           .FitToPagesWide = 1
       End With
       .ExportAsFixedFormat Type:=xlTypePDF, fileName:=fpath & fname, _
                Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
       Application.DisplayAlerts = False
        .Delete
       Application.DisplayAlerts = True
    End With
 Application.ScreenUpdating = True: Application.Calculation = xlCalculationAutomatic
End Sub

请在测试后发送一些反馈。

相关问题