将SaveAs2对话框文件类型与Application.FileDialog

时间:2016-04-04 20:43:45

标签: vba ms-word word-vba word-2013

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

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

这很好用,用户会看到一个保存对话框,选择一个位置并保存文件,但有些事情是不正确的:

enter image description here

显示的类型与VBA中指定的类型不匹配,这怎么可能正确?它仍然保存为类型" PDF"没有问题,即使在显示" DOCX"作为"另存为类型"中的文件类型落下。还有" fileName.pdf"没有放在"文件名"框,就好像对话框不知道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

那么真正的问题(我猜)是如何获得&#34; Application.FileDialog&#34;在&#34;保存类型&#34;下显示您想要保存的正确类型。下拉,这已经被@PatricK回答了。感谢大家的帮助,我为这个问题的最初混淆性质道歉。

1 个答案:

答案 0 :(得分:1)

我很惊讶SaveAs2会给你一个诚实的提示 - 只有一个新文件,.Save会给你提示。

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

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

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

截图示例:
ResultingFileDialogBox