如何解决Excel VBA打印,使用Range.ExportAsFixedFormat实现自动文件名和位置
https://www.contextures.com/excelvbapdf.html 以下内容很完美,但它可以打印整张纸。
全线程
Sub PDFActiveSheet()
'www.contextures.com
'for Excel 2010 and later
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
但是我遇到了这个问题
'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`
我要完成的唯一事情是打印一个范围(最好是命名)来代替整个工作表。我创建了暗淡区域并设置了一个范围来代替“ wsA”表格,但它很容易出错。
Dim rnG As Range
Set rnG = Range("Y1:AG46")
rnG.ExportAsFixedFormat _
是我仅添加的几行。它会按我想要的方式工作,但是间歇性地运行,我也不知道为什么。它将整个ExportFileAsFixedFormat子文本显示为黄色,并指向无法识别指定的范围。
解决方法
我怀疑这是因为您没有使范围合格。试试
Set rnG = wsA.Range("Y1:AG46")
只有在wsA
是活动工作表的情况下,没有资格验证才能正常工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。