自动保存我保存的任何电子表格的 pdf 副本

问题描述 投票:0回答:1

我是一名网络开发人员,所以对代码并不陌生,但我从不使用 VBA。我编写了一个宏,我认为它会自动将任何 .xslx 保存为 pdf(除了 .xslx 之外)在同一目录中。这是代码

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim myPath As String
    Dim myFileName As String

    myPath = ThisWorkbook.Path
    myFileName = ThisWorkbook.Name

    ' Remove the .xlsx extension from the file name
    myFileName = Left(myFileName, InStrRev(myFileName, ".") - 1)

    ' Save as PDF in the same directory
    ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:=myPath & "\" & myFileName & ".pdf"
End Sub
vba
1个回答
0
投票
  • 您的代码已找到。它是一个工作表事件代码,因此应该位于
    ThisWorkbook
    模块中。

  • 顺便说一句,我建议在文件名上添加时间戳以避免覆盖。
    ' Save as PDF in the same directory
    ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=myPath & "\" & myFileName & Format(Now, "_yyyy.MM.dd_hh.mm.ss") & ".pdf"
© www.soinside.com 2019 - 2024. All rights reserved.