vba - VBA 代码帮助——从表格生成单独的 PDF
问题描述
我正在尝试创建一个宏,它将为工作簿中的选定工作表生成单独的 PDF 文件。我在网上找到了这段代码,效果很好,它将所有选定的工作表放在一个 PDF 中。我需要将每个选定的工作表作为单独的 PDF。任何帮助将不胜感激!
我是 VBA 的初学者。再次感谢!
Sub PDFActiveSheet()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile
'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
解决方案
分隔工作表以分隔 PDF 文件
Sub ExportToPDFs()
' PDF Export Macro
' Change C:\Exports\ to your folder path where you need the diles saved
' Save Each Worksheet to a separate PDF file.
Dim ws As Worksheet
For Each ws In Worksheets
ws.Select
nm = ws.Name
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\Excel\Desktop\test\" & nm & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Next ws
End Sub
推荐阅读
- html - 垂直和水平居中对齐容器 div 内的图像和文本
- hibernate - 如何通过仅访问数据库一次来将对象列表存储在数据库中?
- swift - 当应用程序在 iOS12 中进入后台时,URLSessionDelegate 的 didWriteData 不会调用
- laravel - 不能使用多个项目
- ios - 未找到 GStreamer Xcode 10.1 gst/gst.h
- python - 为函数内的全局变量赋值
- angular - 验证应用于文本框
- sql - 使用 NULLIF 除以零
- mysql - 匹配多个表获取角色名称
- c# - Visual Studio 2017 中对象资源管理器上的可见性私有字段