我是Excel宏的新手。我尝试制作一个"另存为pdf"按钮。我写了这样的代码:
Sub save_as_pdf()
'
' save_as_pdf Macro
' Saves sheet as PDF
'
Dim Path As String
Dim filename As String
Path = "/Users/Adrian/Desktop/"
filename = ThisWorkbook.Sheets("Controller").Range("B20")
PathAndFilename = Path & filename & ".pdf"
MsgBox "Saved file as: " & PathAndFilename
Sheets("View").Select
Application.DisplayAlerts = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
PathAndFilename, Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Application.DisplayAlerts = True
End Sub
我需要Range("B20")
,因为我根据一些in-excel逻辑保留了一个文件名。
MsgBox生成有效的路径和文件名。
然而,当我运行这个时,我会在打印时遇到错误#34;和"运行时错误1004"突出显示ActiveSheet.ExportAsFixedFormat ...
答案 0 :(得分:1)
在要导出的工作表中设置打印区域。
同时验证我预期的路径\和驱动器号,例如C:\
以下为我工作
Option Explicit
Sub save_as_pdf()
Dim Path As String
Dim filename As String
Dim PathAndFileName As String
Path = "C:\Users\User\Desktop\" ' "C:\Users\Adrian\Desktop\"
filename = ThisWorkbook.Sheets("Controller").Range("B20")
PathAndFileName = Path & filename & ".pdf"
MsgBox "Saved file as: " & PathAndFileName
Sheets("View").Select
Application.DisplayAlerts = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
PathAndFileName, Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
Application.DisplayAlerts = True
End Sub