【问题标题】:Export excel graphs to horizontal PDF with VBA使用 VBA 将 Excel 图形导出为水平 PDF
【发布时间】:2018-05-26 15:37:33
【问题描述】:

我有以下 VBA 代码,它基本上从 Excel 工作簿的工作表中获取图表并将它们粘贴到 PDF 文档中:

Sub Graphics()

    Dim s As Workbook
    Dim ws As Worksheet, wsTemp As Worksheet
    Dim chrt As Shape
    Dim tp As Long
    Dim File As String
    Dim NewFileName As String
    Dim Path As String

    Application.DisplayAlerts = False

    Application.ScreenUpdating = False

    'Here I define where the excel file is:
    SourcePath = "\\ukfs1\users\gabriem\Documents\Misproyectos\BigPromotions\QAPromo"

    'Name of excel file that contains the graphs:
    File = "graphicator.xlsx"

    'Open the excel file:
    Set s = Workbooks.Open(SourcePath & "\" & File)

    'Name of the PDF I will create with the excel graphs:
    NewFileName = "\\ukfs1\users\gabriem\Documents\Mis proyectos\BigPromotions\QAPromo\test_pdf.pdf"

    'Name of the excel sheet I want to export to PDF:
    Set ws = s.Sheets("Negocios")

    Set wsTemp = s.Sheets.Add

    tp = 2
    ts = 5

    'Copy-Pasting process:
    With wsTemp
        For Each chrt In ws.Shapes
            chrt.Copy
            wsTemp.Range("A1").PasteSpecial
            Selection.Top = tp
            Selection.Left = ts
            tp = tp + Selection.Height + 50
        Next
    End With

    wsTemp.ExportAsFixedFormat Type:=xlTypePDF, Filename:=NewFileName, Quality:=xlQualityStandard, _
       IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

    wsTemp.Delete

 LetsContinue:
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue

End Sub

虽然代码运行良好,但它生成的输出在图形上不够充分,因为许多图形被剪切(其中一半在另一页中)。所以,我希望生成的 PDF 是水平的,但一直找不到答案。不是 Excel 的问题,而是 VBA 代码创建的新 PDF:

非常感谢!!

【问题讨论】:

标签: excel vba pdf


【解决方案1】:

我在从图表生成 PDF 时也遇到了类似的问题。解决方案是使用ChartObject 而不是Shape,并使用.CopyImage 来获取图表的图片,而不是尝试复制实际图表。所以代码看起来更像:

Dim chrt as ChartObject
:
For Each chrt in ws.ChartObjects
    chrt.CopyPicture
    wsTemp.Paste
    Selection.Top = tp
    Selection.Left = ts
    ts = ts + Selection.Width + 50
 Next

然后您还应该在工作表中设置打印区域,并设置页面设​​置以按您希望 pdf 的方式对文档进行分页 - 使用横向格式(如果这就是您所说的“水平”)。您的图表数量是否超过了一个页面的容量?如果是这样,您将需要检查累积宽度以确保图表不会跨越页面边界。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-09
    • 2020-06-27
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2016-12-06
    相关资源
    最近更新 更多