将多个工作表导出为PDF

时间:2018-05-28 09:18:51

标签: excel vba excel-vba

我想将单页“Verification”和“Deisgn Overview”导出到单个PDF。最下面,可以看到整个代码。

使用时

Set wsA = ActiveSheet

代码工作正常。但是,当我将该定义更改为

Set wsA = Sheets(Array("Verification", "Design Overview")).Select

代码归结为错误处理。

多张表选择是否会干扰strName或代码出错的位置?

此外,我想取消选择多张工作表,并且只在导出后选择了活动工作表。

Sub Export()

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
Set wsA = Sheets(Array("Verification", "Design Overview")).Select
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 = "Example"
strPathFile = strPath & strFile

'User can enter name and select folder for the file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
    FileFilter:="PDF (*.pdf), *.pdf", _
    Title:="Select folder and filename to save")

'Export to PDF if a folder is selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=True
'Confirmation message with file info
'MsgBox "File has been created: " _
  '& vbCrLf _
  '& myFile
 End If

exitHandler:
Exit Sub
errHandler:
MsgBox "Could not export file", vbCritical, "Export"
Resume exitHandler

ThisWorkbook.Sheets("Design Overview").Select

End Sub

提前致谢!

1 个答案:

答案 0 :(得分:1)

如果要根据变量选择工作表,这是一种很好的方法:

Dim mySh As Sheets
Set mySh = Worksheets(Array(Worksheets(1).Name, Worksheets(2).Name))
mySh.Select

但是,正如评论中提到的那样,it is really very rare that you need to Select and Activate objects in Excel - 您可以引用它们,将它们集合在一起并使用它们来做您需要的任何事情:

Sub TestMe()

    Dim myWs As Worksheet
    Dim wsCol As New Collection

    wsCol.Add Worksheets(1)
    wsCol.Add Worksheets(2)

    For Each myWs In wsCol
        myWs.Cells(1, 1) = "TEST"
    Next myWs

    Dim mySh As Sheets
    Set mySh = Worksheets(Array(Worksheets(1).Name, Worksheets(2).Name))
    mySh.Select

End Sub

因此,您会得到两个错误 - 执行速度和对代码的更好控制(因此错误更少)。