将 SaveAs2 对话框文件类型匹配到 Application.FileDialog

Match SaveAs2 Dialog File Type To Application.FileDialog

假设您想要一个按钮,用户可以单击该按钮并将当前文件的副本另存为 PDF(Documentation):

Application.ActiveDocument.SaveAs2 fileName:="fileName.pdf", FileFormat:=wdFormatPDF

这工作正常,用户会看到一个保存对话框,选择一个位置并保存文件,但是有几处不正确:

显示的类型与VBA中指定的不匹配,这怎么可能是正确的?即使在 "Save as Type" 下拉列表中显示 "DOCX" 作为文件类型后,它仍然可以毫无问题地保存为类型 "PDF"。 "fileName.pdf" 也没有放在 "File Name" 框中,就好像对话框不知道 VBA 代码中设置的选项(This same issue is also referenced in this post)。

更新 1

再次查看我的代码后,我现在意识到 SaveAs2 方法没有显示对话框菜单,代码的正确版本(简化)可以描述为:

Dim selected As String: selected = Application.FileDialog(msoFileDialogSaveAs).Show()
Dim filePath As String

If selected <> 0 Then
    filePath = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
    Application.ActiveDocument.SaveAs2 fileName:=Split(filePath, ".")(0), FileFormat:=wdFormatPDF
End If

那么真正的问题(我猜)是如何让 "Application.FileDialog" 在 "Save as type" 下拉列表中显示您希望保存的正确类型,这已经得到解答通过@PatricK。感谢大家的帮助,对于这个问题最初的困惑,我深表歉意。

我很惊讶 SaveAs2 老实说会给您带来提示 - 只有新文档和 .Save 才会给您提示。

如果您想获得与该提示类似的内容,请使用 Application.FileDialog with type msoFileDialogSaveAs

使用下面的代码(也许作为插件更适合):

Option Explicit

Sub MySaveAs()
    Dim oPrompt As FileDialog, i As Long, sFilename As String
    Set oPrompt = Application.FileDialog(msoFileDialogSaveAs)
    With oPrompt
        ' Find the PDF Filter from Default Filters
        For i = 1 To .Filters.Count
            'Debug.Print i & " | " & .Filters(i).Description & " | " & .Filters(i).Extensions
            ' Locate the PDF filter
            If InStr(1, .Filters(i).Description, "PDF", vbTextCompare) = 1 Then
                .FilterIndex = i
                Exit For
            End If
        Next
        ' Change the title and button text
        .Title = "Saving """ & ActiveDocument.Name & """ to PDF format"
        .ButtonName = "Save to PDF"
        ' Default name
        .InitialFileName = ActiveDocument.Name
        ' Show the Prompt and get Filename
        If .Show = -1 Then
            sFilename = .SelectedItems(1)
            Debug.Print "Final filename: " & sFilename
            ' Save the file as PDF
            ActiveDocument.SaveAs2 sFilename, wdFormatPDF
        End If
    End With
    Set oPrompt = Nothing
End Sub

截图示例: