VBA文件对话框的应用(VBA打开文件、VBA选择文件、VBA选择文件夹) 您所在的位置:网站首页 vba打开指定文件夹的代码 VBA文件对话框的应用(VBA打开文件、VBA选择文件、VBA选择文件夹)

VBA文件对话框的应用(VBA打开文件、VBA选择文件、VBA选择文件夹)

2024-03-11 19:25| 来源: 网络整理| 查看: 265

在VBA中经常要用到文件对话框来进行打开文件、选择文件或选择文件夹的操作。用Microsoft Office提供的文件对话框比较方便。用法如下Application.FileDialog(fileDialogType)fileDialogType      MsoFileDialogType 类型,必需。文件对话框的类型。

  MsoFileDialogType 可为以下 MsoFileDialogType 常量之一。    msoFileDialogFilePicker  允许用户选择文件。    msoFileDialogFolderPicker  允许用户选择一个文件夹。    msoFileDialogOpen  允许用户打开文件。用Excel打开。    msoFileDialogSaveAs  允许用户保存一个文件。

分别举例如下:

 

1、msoFileDialogFilePicker 1)选择单个文件

 

Sub SelectFile() '选择单一文件 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() '选择多个文件 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  

2、msoFileDialogFolderPicker

文件夹仅能选择一个

 

Sub SelectFolder() '选择单一文件 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

 

3、msoFileDialogOpen4、msoFileDialogSaveAs使用方法与前两种相同只是在.show可以用.Execute方法来实际打开或者保存文件。

例如:

 

Sub SelectFile() '选择单一文件 With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False '单选择 .Filters.Clear '清除文件过滤器 .Filters.Add "Excel Files", "*.xls;*.xlw" .Filters.Add "All Files", "*.*" '设置两个文件过滤器 .Execute End With End Sub  

 

 

另见:

 

《用Excel VBA选择文件、高容错性地打开文件》

http://justsee.iteye.com/blog/1468743

 

 

转自因特网,感谢因特网的雷锋们!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有