【问题标题】:Get location or directly open file after printing to PDF using Workbook.PrintOut() method in VBA Excel使用 VBA Excel 中的 Workbook.PrintOut() 方法打印到 PDF 后获取位置或直接打开文件
【发布时间】:2021-05-29 15:02:42
【问题描述】:

我正在编写一个将整个工作簿导出为 PDF 文件的宏。

生成过程正常,但现在我想让它在完成后打开新生成的文件。问题是由于文件名不是预定义的,我不能简单地使用它的路径和名称打开它。

我正在使用 PrintOut 方法生成之前选择的 ActivePrinter 为“Microsoft Print to PDF”,或者如果发生错误,则要求用户使用 Application.Dialogs(xlDialogPrinterSetup).Show 手动选择它。

这是这部分的一个sn-p:

Call set_printer

ActiveWorkbook.PrintOut Copies:=1, PrintToFile:=True

... set_printer() 在哪里:

Public Sub set_printer()

    On Error GoTo problem_with_pdf_printer

    Application.ActivePrinter = "Microsoft Print to PDF"
    
Done: Exit Sub
    
problem_with_pdf_printer:

    MsgBox "There is a problem with the Microsoft Print to PDF printer." & Chr(13) & Chr(13) & _
        "Select another one manually!", vbInformation, "Warning!"
    
    Application.Dialogs(xlDialogPrinterSetup).Show
    
End Sub

有没有办法在执行该方法后捕获新的文件位置?我想到的另一个想法是自定义“选择文件位置”-对话可以帮助我预定义文件路径,但遗憾的是我不知道如何实现。

非常感谢您,如果您有任何建议和想法,我将非常高兴!

【问题讨论】:

    标签: excel vba pdf-generation


    【解决方案1】:

    转换为 pdf 似乎是要走的路。

    Sub test()
        Dim Wb As Workbook
        Dim fn As String
        
        Set Wb = ThisWorkbook
        
        ChDir ThisWorkbook.Path 'C:\yourpath
        
        fn = "test.pdf"
        fn = Application.GetSaveAsFilename(fn, FileFilter:="PDF Files,*.pdf")
            
        Wb.ExportAsFixedFormat xlTypePDF, fn, OpenAfterPublish:=True
    End Sub
    

    【讨论】:

    • 谢谢!对我帮助最大的是 Application.GetSaveAsFilename() 方法。我用它来捕获路径,然后我使用 PrintOut() 方法导出文件并使用 Shell 或 FollowHyperlink() 方法简单地打开它。
    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2019-05-03
    • 2013-10-11
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    相关资源
    最近更新 更多