Excel VBA将选定的工作表导出为选定份数的PDF

时间:2015-02-21 19:56:10

标签: excel vba pdf

工作簿由4张隐藏的工作表组成。如果要包含在pdf中,则每张表中的A1的值为1,如果不包括,则为0。

作为一个新手,这是我到目前为止所得到的:

Private Sub CommandButton21_Click()

Application.ScreenUpdating = False

Sheets("print1").Visible = True
Sheets("print2").Visible = True
Sheets("print3").Visible = True
Sheets("print4").Visible = True

ThisWorkbook.Sheets(Array("print1", "print2")).Select  

iPtr = InStrRev(ActiveWorkbook.FullName, ".")

If iPtr = 0 Then
sFileName = ActiveWorkbook.FullName & ".pdf"
Else
sFileName = Left(ActiveWorkbook.FullName, iPtr - 1) & ".pdf"
End If

sFileName = Application.GetSaveAsFilename(InitialFileName:=sFileName, FileFilter:="PDF Files (*.pdf), *.pdf")

If sFileName = "False" Then Exit Sub

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=sFileName, Quality:=xlQualityStandard, openAfterPublish:=True

Sheets("print1").Visible = False
Sheets("print2").Visible = False
Sheets("print3").Visible = False
Sheets("print4").Visible = False

Application.ScreenUpdating = True

End Sub

1)必须有可能使这更优雅;表格(数组(“print1”,“print2”......))。Visible = True将显示4张,但如果设置为false,则只会隐藏print1。

2)如何从A1获取值以构建具有正确表格的pdf?

3)我也希望在同一个pdf中有几张总页数。如果我要在同一个pdf中导出print1和print3,我可能想要2份; print1,print3,(和重读:) print1,print3,在同一个pdf文件中。副本的数量来自A2。

1 个答案:

答案 0 :(得分:0)

请参阅下面的代码,该代码解决了问题的第1部分和第2部分。我删除了iPtr if语句行,因为当sFilename设置为等于Application.GetSaveAsFileName时,它们为变量sFilename输入的任何值都将被覆盖。

Private Sub CommandButton21_Click()

Application.ScreenUpdating = False
sheet_name_array = Array("print1", "print2", "print3", "print4")
sfilename = Application.GetSaveAsFilename(InitialFileName:=sfilename, _
FileFilter:="PDF Files (*.pdf), *.pdf")

If sfilename = "False" Then Exit Sub
For Each sheet_name In sheet_name_array
    Sheets(sheet_name).Visible = True
    If sheets(sheet_name).Range("A1") = 0 Then
        sheets(sheet_name).visible = false
    End If
Next

activeworkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=sfilename, _
Quality:=xlQualityStandard, openAfterPublish:=True

For Each sheet_name In sheet_name_array
  Sheets(sheet_name).Visible = False
Next

Application.ScreenUpdating = True
End Sub