【问题标题】:How to automatically select save button when creating a PDF using如何在使用创建 PDF 时自动选择保存按钮
【发布时间】:2017-12-02 17:05:31
【问题描述】:

我的代码运行良好,并从工作表创建了 PDF。但我希望这种情况发生,而不必按下文件路径的保存单选按钮。 还是我需要创建一个确切的文件名并没有选择地保存

    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(), "ddmmyyyy\_hhmm")

    strPath = wbA.Path
    If strPath = "" Then
      strPath = Application.DefaultFilePath
    End If
    strPath = strPath & "\"

    strName = Replace(wsA.Name, " ", "")
    strName = Replace(strName, ".", "_")

    strFile = strName & "_" & strTime & ".pdf"
    strPathFile = strPath & strFile

    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:
    CommandButton2.Visible = True
    CommandButton1.Visible = False     
    Exit Sub

errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler
End Sub

【问题讨论】:

  • 如果您不想要保存对话框,您需要在ExportAsFixedFormat 中指定Filename:=myFileWithFullPath 的完整路径。所以它直接保存文件而不选择。如果您需要使用对话框选择路径,则需要自己按保存按钮。

标签: excel pdf-generation vba


【解决方案1】:

在运行时创建一个准确的文件名并保存为例如:-

ActiveSheet.ExportAsFixedFormat _ 
Type:=xlTypePDF _
Filename:= destfolder & PDF_Filename _
Quality:=xlQualityStandard _
IncludeDocProperties:=True _
IgnorePrintAreas:=False _
OpenAfterPublish:=True

【讨论】:

  • 但@tim 应该在这个答案中使用wsA 而不是ActiveSheet。首先将活动工作表定义为wsA 是一个非常好的决定。
  • @Peh...是的,通过activesheet我的意思是一样的...我只是将它作为示例代码分享...
【解决方案2】:

您也可以尝试以下方法:

Application.SendKeys("%s")

上面的Sends keystrokes to the active application在这里表示Alt+S,这是Save的快捷键...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2019-12-18
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多