vba学习系列(1)--打开对话框系列⽂章⽬录
⽂章⽬录
前⾔
学会长⼤,学会承受!!
⼀、vba打开⽂件对话框
只需要修改初始路径即可!!
.InitialFileName = ThisWorkbook.Path & "\"
1.对话框路径为指定路径
代码如下(路径为当前⽂件所在路径):
Sub 汇总()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.Filters.Clear
.Filters.Add "CSV","*.CSV",1
.InitialFileName = ThisWorkbook.Path & "\"
If .Show =-1 Then
For Each vrtSelectedItem In .SelectedItems
If vrtSelectedItem <>"" Then
InputData(vrtSelectedItem)
End If
Exit For
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Sub
代码如下(路径为⾃定义路径):
Sub 汇总()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.Filters.Clear
.Filters.Add "CSV","*.CSV",1
.InitialFileName ="\\192.168.177.27\研发"& "\"
If .Show =-1 Then
For Each vrtSelectedItem In .SelectedItems
If vrtSelectedItem <>"" Then
InputData(vrtSelectedItem)
End If
Exit For
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Sub
2.对话框路径为上次操作使⽤路径
vba自学好学吗代码如下(最简略):
Sub OpenFile()
fileToOpen = Application _
.GetOpenFilename("Dat Files (*.DAT), *.dat, Text Files (*.txt), *.txt") End Sub
代码如下(实例应⽤,删除路径也可以):
Sub 汇总()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.Filters.Clear
.InitialFileName ="Dat Files (*.CSV), *.csv, Text Files (*.txt), *.txt" If .Show =-1 Then
For Each vrtSelectedItem In .SelectedItems
If vrtSelectedItem <>"" Then
InputData(vrtSelectedItem)
End If
Exit For
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Sub
⼆、参考源码
1.单个⽂件
代码如下(⽰例):
.
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
3.其它
代码如下(⽰例):
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
代码如下(⽰例):
.Filters.Clear '清除⽂件过滤器
.Filters.Add "Excel Files","*.xls;*.xlw"
.Filters.Add "All Files","*.*" '设置两个⽂件过滤器
.Execute
End With
End Sub
总结
分享:
乐曲本⾝单纯如镜,你之所以能够从⽩雪中听出那么深沉的悲伤,只有⼀个原因,那个⼀直没有从噩梦中醒来的⼈,恰恰就是你⾃⼰。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论