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

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

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

分别举例如下:

1、msoFileDialogFilePicker 
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

2、msoFileDialogFolderPicker

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

文件夹仅能选择一个

3、msoFileDialogOpen
4、msoFileDialogSaveAs

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




转载于:https://www.cnblogs.com/p4759521/articles/2203828.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值