使用excel中的按钮将数据范围另存为PDF

时间:2015-06-29 08:51:11

标签: excel vba excel-vba

我的代码会在点击Excel工具栏中的按钮时弹出一个保存对话框:

Sub SavePDF()
Dim X
X = Application.GetSaveAsFilename(InitialFileName:=Range("F8") & "_" & Range("F6"), _
     FileFilter:="PDF files, *.pdf", _
     Title:="Save PDF File")
If TypeName(X) = "Boolean" Then
Else
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=X, Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    End If
End Sub

...我需要的是添加一些东西,只有在点击按钮时才能保存一定范围的数据。我的范围是:B2到J44。当我点击保存按钮时,它会保存我不想要的整张纸。

提前致谢。

1 个答案:

答案 0 :(得分:1)

请尝试以下操作。

Option Explicit
Sub CreatePDF()
    Dim wSheet As Worksheet
    Dim vFile As Variant
    Dim sFile As String

    Set wSheet = ActiveSheet
    sFile = Replace(Replace(wSheet.Name, " ", ""), ".", "_") _
            & "_" _
            & Format(Now(), "yyyymmdd\_hhmm") _
            & ".pdf"
    sFile = ThisWorkbook.Path & "\" & sFile

    vFile = Application.GetSaveAsFilename _
    (InitialFileName:=sFile, _
        FileFilter:="PDF Files (*.pdf), *.pdf", _
        Title:="Select Folder and FileName to save")

    If vFile <> "False" Then
    wSheet.Range("B2:J44").ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=vFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

    MsgBox "PDF file has been created."
    End If
End Sub

参见示例here

文件另存为 SheetName_TodaysDate_HoursMinutes

如果您想添加秒数,只需在 ss

旁边添加 _hhmmss