使用VBA将Excel图表导出为水平PDF

时间:2017-12-12 20:49:33

标签: excel vba pdf

我有以下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:

enter image description here enter image description here

非常感谢!!

1 个答案:

答案 0 :(得分: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的显示方式 - 使用格局格式(如果你的意思是“水平”)。你有更多的图表而不是页面上的图表吗?如果是这样,您需要检查累积宽度以确保图表不跨越页面边界。