文件选择器,如何指定文件类型?

时间:2013-11-08 10:20:29

标签: excel vba excel-vba

我有以下代码打开文件选择器,让用户选择一个文件。

Sub SelectFiles(ByRef test As String)

    Dim iFileSelect As FileDialog
    Set iFileSelect = Application.FileDialog(msoFileDialogFilePicker)

    Dim vrtSelectedItem As Variant  

        If iFileSelect.Show = -1 Then            

            For Each vrtSelectedItem In iFileSelect.SelectedItems
                test = vrtSelectedItem
            Next vrtSelectedItem

        End If

    Set iFileSelect = Nothing

End Sub

我希望它只显示某种类型的文件(在本例中为XML),用户可以选择任何文件类型。

我经历了一些有创意的谷歌搜索,但似乎无法找到解决方案,我觉得它应该很简单。

1 个答案:

答案 0 :(得分:12)

Sub Main()
    Dim test As String
    SelectFiles test
    Debug.Print test
End Sub

Sub SelectFiles(ByRef test As String)

    Dim iFileSelect As FileDialog
    Set iFileSelect = Application.FileDialog(msoFileDialogOpen)
    With iFileSelect
        .AllowMultiSelect = True
        .Title = "Select XML Files"
        .Filters.Clear
        .Filters.Add "Extensible Markup Language Files", "*.xml"
        .InitialView = msoFileDialogViewDetails
        If .Show = -1 Then
            Dim vrtSelectedItem
            For Each vrtSelectedItem In iFileSelect.SelectedItems
                test = vrtSelectedItem
            Next vrtSelectedItem
        End If
    End With
    Set iFileSelect = Nothing
End Sub