【办公-excel】VBA 选择文件、文件夹

1、选择单个文件

Sub SelectFile()
    '选择单一文件
    'www.okexcel.com.cn
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        '单选择
        .Filters.Clear
        '清除文件过滤器
        .Filters.Add "Excel Files", "*.xls;*.xlw"
        .Filters.Add "All Files", "*.*"
        '设置两个文件过滤器
        If .Show = -1 Then
            'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。
            MsgBox "您选择的文件是:" & .SelectedItems(1), vbOKOnly + vbInformation, "智能Excel"
        End If
    End With
End Sub

2、选择多个文件

Sub SelectFile()
    '选择多个文件
    'www.okexcel.com.cn
    Dim l As Long
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = True
        '单选择
        .Filters.Clear
        '清除文件过滤器
        .Filters.Add "Excel Files", "*.xls;*.xlw"
        .Filters.Add "All Files", "*.*"
        '设置两个文件过滤器
        .Show
        'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。
        For l = 1 To .SelectedItems.Count
            MsgBox "您选择的文件是:" & .SelectedItems(l), vbOKOnly + vbInformation, "智能Excel"
        Next
    End With
End Sub

3、选择文件夹

Sub SelectFolder()
    '选择单一文件
    'www.okexcel.com.cn
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = -1 Then
        'FileDialog 对象的 Show 方法显示对话框,并且返回 -1(如果您按 OK)和 0(如果您按 Cancel)。
            MsgBox "您选择的文件夹是:" & .SelectedItems(1), vbOKOnly + vbInformation, "智能Excel"
        End If
    End With
End Sub


猜你喜欢

转载自blog.csdn.net/chenlu5201314/article/details/80344018