18

VBScript - 弹出“文件选择对话框”方法大全!

 4 years ago
source link: http://www.cnblogs.com/bitssea/p/12684322.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文记录,VBScript 中,各种打开 “文件选择对话框” 的方法。

jARbe2r.png!web

实现方法-1 (mshta.exe):

首先,我们要实现的就是,弹出上面的这个“文件选择对话框”。

这种方法是通过,Shell 对象,打开 mshta.exe 程序,执行一个 .hta 文件,从而打开窗口,

这种方法,其实是写了一个简单的 hta (HTML Applicaiton) 文件,

然后,这个 hta 文件,打开了 “选择文件对话框”,代码如下:

'打开对话框
Set wShell = CreateObject("WScript.Shell")
Set oExec = wShell.Exec("mshta.exe ""about:<input type=file id=FILE><script>FILE.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);</script>""")

'输出选择的,文件的路径
File_Selected = oExec.StdOut.ReadLine
MsgBox File_Selected

实现方法-2 (InternetExplorer.Application):

这种方法是通过,InternetExplorer.Application 对象来实现的,

先创建一个 IE 的对象,然后写一个 HTML 文件,然后执行这个文件,从而打开窗口,

这种方法,虽然调用的对象,和方法1不同,但其根本原理和方法1,是完全一样的,

'打开对话框
Set IE = CreateObject("InternetExplorer.Application")
With IE
    .Visible = False
    .Navigate("about:blank")
    Do Until .ReadyState = 4 : Loop
        With .Document
            .Write "<html><body><input id='f' type='file'></body></html>"
                With .All.f
                    .Focus
                    .Click
                        Result = .Value
                End With
        End With
        .Quit
End With
Set IE = Nothing

'输出选择的,文件的路径
File_Selected = Result
MsgBox File_Selected

实现方法-3 (Excel.Application):

这种方法是通过,Excel.Application 对象来实现的,

是通过 Excel Object 自带的,GetOpenFilename 方法,直接打开的对话框,

个人觉得,这个方法是最方便的,代码如下:

'打开对话框
Set oExcel=CreateObject("Excel.Application")
    FileFilter = "CSV Files (*.csv),*.csv"
    FilterIndex = default
    Title = ""
    ButtonText = ""
    MultiSelect = False
File_Selected= oExcel.GetOpenFilename (FileFilter, FilterIndex, Title, ButtonText, MultiSelect)

'输出选择的,文件的路径
MsgBox File_Selected

实现方法-4 (Excel.Application):

这种方法是通过,Excel.Application 对象来实现的,

是通过 Excel Object 自带的,FileDialog 方法,直接打开的对话框,

另外,这种方法,是支持选择多个文件的,多选的时候,返回的是一个 Array,

这就是,为什么你看到 FileDialog.SelectedItems(1) 这段代码结尾有个 (1),代表选择了第一个 Item,

还有,这是这种方法,是要提前设置常量的,一共四种常量,对应四种不同的窗口,

这种方法,本质上来源于 VBA,所以,方法3和方法4,在 VBA 里也可以使用,

我个人比较喜欢,这种方法,因为看上去很清晰,而且可以设置初始路径,很方便,

'设置常量
Const msoFileDialogOpen = 1
Const msoFileDialogSaveAs = 2
Const msoFileDialogFilePicker = 3
Const msoFileDialogFolderPicker  = 4

'打开对话框
Set oExcel = CreateObject("Excel.Application")
Set FileDialog = oExcel.FileDialog(msoFileDialogFilePicker)

'添加筛选条件
FileDialog.Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1 

'设置初始路径
FileDialog.InitialFileName = "C:\" 

'弹出对话框
FileDialog.show()

'输出选择的,文件的路径
File_Selected = FileDialog.SelectedItems(1)
MsgBox File_Selected

实现方法-5 (Word.Application):

这种方法和上面的方法是完全一样的,

只是使用的是,Word.Application 对象而已,

所以,可以推测,微软的办公套件对象,应该都可以用来实现这个功能,

'设置常量
Const msoFileDialogOpen = 1
Const msoFileDialogSaveAs = 2
Const msoFileDialogFilePicker = 3
Const msoFileDialogFolderPicker  = 4

'打开对话框
Set oWord = CreateObject("Word.Application")
Set FileDialog = oWord.FileDialog(msoFileDialogFilePicker)

'设置初始路径
FileDialog.InitialFileName = "C:\" 

'弹出对话框
FileDialog.show()

'输出选择的,文件的路径
File_Selected = FileDialog.SelectedItems(1)
MsgBox File_Selected

实现方法-6 (Scripting.FileSystemObject):

这种方法,就不去详细说明了,因为其根本原理,其实和方法1,方法2,是一样的,

只不过是,调用的 Object 不同而已,但,也列出来供大家参考,

Function BrowseForFile()
    With CreateObject("WScript.Shell")
        Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
        Dim tempFolder : Set tempFolder = fso.GetSpecialFolder(2)
        Dim tempName : tempName = fso.GetTempName() & ".hta"
        Dim path : path = "HKCU\Volatile Environment\MsgResp"
        With tempFolder.CreateTextFile(tempName)
            .Write "<input type=file name=f>" & _
            "<script>f.click();(new ActiveXObject('WScript.Shell'))" & _
            ".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value);" & _
            "close();</script>"
            .Close
        End With
        .Run tempFolder & "\" & tempName, 1, True
        BrowseForFile = .RegRead(path)
        .RegDelete path
        fso.DeleteFile tempFolder & "\" & tempName
    End With
End Function

MsgBox BrowseForFile

实现方法-7 (Shell.Application):

这种方法呢,算是 VBScript 最本土的方法了,

没有调用任何第三方的 Object,只用了自己自带的 Shell.Application 对象,

但是,其实这种方法,只能选择文件夹,虽然确实能看到所有文件,但是要是真选了,就会报错!

但是,网上还是有人,在这种基础上做出了改进,也变得能够选择文件,并且返回文件路径,

Function BrowseForFile()
    Dim shell : Set shell = CreateObject("Shell.Application")
    Dim file : Set file = shell.BrowseForFolder(0, "Choose a file:", &H4000, "C:\")
    BrowseForFile = file.self.Path
End Function

MsgBox BrowseForFile

实现方法-8 (MSComDlg.CommonDialog):

其实,这才是最古老的方法,看上去十分的简洁,好用,

但是,注意,这是 Windows XP 时代的代码,现在 Windows 7 已经不支持了,

当然,你是可以想办法让 Windows 7 支持,这个 Object,

如果有人,对这种古老的方法感兴趣,就去看我的参考阅读吧,

但是,很麻烦,几乎不太值得了,所以,放在这,作为个借鉴吧,

Set oDialog = CreateObject("MSComDlg.CommonDialog")

With oDialog
    .Filter = "*.txt"   
    .InitDir = "C:"   
    .MaxFileSize = 256   
    .Flags = &H80000 + &H4 + &H8 
End With

MsgBox oDialog.FileName

实现方法-9 (UserAccounts.CommonDialog):

这是另一个古老的方法,看上去十分的简洁,同样是 Windows XP 时代的代码,

现在 Windows 7 已经不支持了,放在这,作为个借鉴吧,

我也没办法测试这两个方法,因为我没有 XP 系统,

<br>

'Set oDialog = CreateObject("UserAccounts.CommonDialog")

oDialog.Filter = "Text Files|*.txt|All Files|*.*"
oDialog.FilterIndex = 1
oDialog.InitialDir = "C:\Program Files"
Result = oDialog.ShowOpen

MsgBox oDialog.FileName

篇尾总结

我个人比较喜欢,方法4,方便清晰,又简洁。

这篇文章差不多囊括了所有常见的 “文件选择对话框” 的实现方法。

如果,以后在发现新的方法了,再来更新!

希望使用 VBScript 的人有帮助。

参考阅读:

  1. VBA - VBScript to open a dialog to select a filepath - Stack Overflow
  2. Windows7 VBScript open file dialog box - fakepath
  3. VBA Files & Directories - Application.GetOpenFileName
  4. Application.GetOpenFilename method (Excel) | Microsoft Docs
  5. MsoFileDialogType enumeration (Office) | Microsoft Docs
  6. FileDialog members (Office) | Microsoft Docs
  7. How to browse for a file in Windows 7
  8. VBScript File Browser · GitHub
  9. Windows 7 Replacement for UserAccounts.CommonDialog in VBScript

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK