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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19856592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:09:02  来源:igfitidea点击:

File selector, How do i specify filetype?

excelvbaexcel-vba

提问by Jon Carlstedt

I have the following code that opens a file selector and lets the user pick a file.

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

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

I would like it to only display files of a certain type (in this case XML) as it is now, the user can select any file type.

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

I have been through some creative Google searches but cant seem to find a solution and I have a feeling that it should be quite simple.

我已经通过一些创造性的谷歌搜索,但似乎无法找到解决方案,我觉得它应该很简单。

回答by

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