Application.FileDialog(msoFileDialogSaveAs),带.pdf作为Filter

时间:2014-01-24 14:13:32

标签: excel excel-vba vba

我希望让用户选择他们要导出的PDF文件的路径和文件名。

我创建了以下内容以显示SaveAs对话框:

Sub Test3()

    Set myFile = Application.FileDialog(msoFileDialogSaveAs)
    With myFile
    .Title = "Choose File"
    .AllowMultiSelect = False
    .ButtonName = "&Save As"
    .initialFilename = "Export"
    .Title = "Save PDF as"
    If .Show <> -1 Then
    MsgBox "You have cancelled"
    Exit Sub
    End If
    FileSelected = .SelectedItems(1)
    End With


    End Sub

FileSelected的值稍后会输入pdf导出代码。

我希望在上面的FileSave对话框中添加一个过滤器,以便它只显示PDF作为文件保存类型。

目前,FileSelected的值最终为“Driveletter:/ Folder / Name。 xlsm ”,因此当我将其输入pdf导出时,它将使用xlsm扩展名保存pdf。 / p>

我已经尝试了.Filter.Clear然后.Filters.Add没有太多运气。

任何帮助都将受到高度赞赏!

3 个答案:

答案 0 :(得分:12)

别介意我弄清楚了:

Sub Test3()

On Error Resume Next
Dim FileSelected As String

FileSelected = Application.GetSaveAsFilename(initialFilename:="Export", _
                                         FileFilter:="PDF Files (*.pdf), *.pdf", _
                                         Title:="Save PDF as")
If Not FileSelected <> "False" Then
MsgBox "You have cancelled"
Exit Sub
End If

If FileSelected <> "False" Then
MsgBox FileSelected 'where FileSelected is what I will be
                    'later feeding into the PDF Export Code
Exit Sub
End If

End Sub

答案 1 :(得分:1)

我在选项列表中添加了一个循环来运行文件类型并选择我想要的那个。它有它的缺点,但是有效...

For I = 1 To .Filters.Count
    fName = .Filters(I).Description
    If fName = "PDF" Then
        .FilterIndex = I
        Exit For
    End If
Next

答案 2 :(得分:0)

您可以使用: .Filters。添加“ * .PDF”,1 要么 .FilterIndex = 25 取决于listindex中PDF的订单号,您可以从“另存为”对话框--->类型中知道它: 子Test3()

Set myFile = Application.FileDialog(msoFileDialogSaveAs)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
.ButtonName = "&Save As"
.initialFilename = "Export"
.Title = "Save PDF as"
.Filters.Add "*.PDF", 1
If .Show <> -1 Then
MsgBox "You have cancelled"
Exit Sub
End If
FileSelected = .SelectedItems(1)
End With


End Sub