提问人:HummBird 提问时间:10/1/2023 最后编辑:HummBird 更新时间:10/2/2023 访问量:84
Excel VBA 打印到 PDF - 带有单元格引用文件名和文件夹路径
Excel VBA Print to PDF - with cell reference file name and folder path
问:
我正在尝试将 excel 报告保存/打印 30 页转换为 PDF。
设置为单元格引用的文件和文件夹路径。
我尝试使用以下代码,请帮我清除最后的问题。
运行时错误“1004”
文档未保存。保存时可能会遇到错误
Sub PrintToPDF()
Dim ws As Worksheet
Dim vDir As String
Dim pdfName As String
Dim fileSaveName As String
Dim separator As String: separator = Application.PathSeparator
Dim FSO As Object
' Set the worksheet to print (e.g., "REPORT" sheet)
Set ws = ThisWorkbook.Sheets("REPORT")
' Get the folder path from INPUT!B6
vDir = ThisWorkbook.Sheets("INPUT").Range("B6").Value
' Get the file name from INPUT!B5
pdfName = ThisWorkbook.Sheets("INPUT").Range("B9").Value
If vDir = "" Or pdfName = "" Then
MsgBox "Folder path or file name is missing. Please provide both a folder path and a file name."
Exit Sub
End If
' Check if the folder exists, and create it if it doesn't
If Dir(vDir, vbDirectory) = "" Then
MkDir vDir
End If
' Check if the file name has a ".pdf" extension
If Right(pdfName, 4) <> ".pdf" Then
pdfName = pdfName & ".pdf"
End If
' Build the full file path
fileSaveName = vDir & separator & pdfName
' Create a FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
' Check if the file already exists
If Not FSO.FileExists(fileSaveName) Then
' Set the print area for the "REPORT" sheet (e.g., A1:AK2107)
ws.PageSetup.PrintArea = "A1:AK2107"
' Export the "REPORT" sheet as PDF and open it after publishing
ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
MsgBox "PDF File Saved in " & vDir
' Clear the print area setting
ws.PageSetup.PrintArea = ""
Else
MsgBox "This PDF file already exists in the same system folder. or May be Opened"
End If
' Release the FileSystemObject
Set FSO = Nothing
End Sub
答:
0赞
Black cat
10/2/2023
#1
当计算机上不存在路径名时,将引发此错误。该方法不会创建不存在的文件夹。首先,您必须创建所有文件夹,然后才能保存文件。文件夹必须一个接一个地创建。
fso.createfolder "C.\users\Username\where\folder1"
fso.createfolder "C.\users\Username\where\folder1\folder2"
之后可以保存文件。
更新:
我检查此代码,然后在浏览器中打开,并在工作表上显示选定的图表示例,或者如果没有,则选择包含几页的整个工作表。
Sub myccc()
filesavename = "C:\users\myname\desktop\mypdf.pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filesavename, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
也就是说,代码没问题。 请试试。
评论
0赞
HummBird
10/2/2023
文件夹被清楚地设置了广告路径引用给单元格。如果我在确切的路径中手动添加具有相同文件名的 pdf。它会发出警报,说这个PDF文件已经存在于同一个系统文件夹中,这意味着我的文件夹和文件名已经明确设置。
0赞
Black cat
10/2/2023
@humm我在答案中添加了一个测试。
评论