VBScript BrowseForFile()函数 - 如何指定文件类型?

时间:2016-07-28 17:52:22

标签: function csv vbscript

我在GitHub上发现了这个功能,它对我需要的东西很有用,但我无法弄清楚如何指定文件类型。它似乎默认为“全部”。

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()

我尝试修改此行:

.Write "<input type=file name=f ><script>f.click()" & _
";(new ActiveXObject('WScript.Shell'))" & _
".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value)" & _
";close();<" & "/" & "script>"

对此:

.Write "<input type=file accept=" & chr(34) & "text/plain" & chr(34) & " name=f ><script>f.click()" & _
";(new ActiveXObject('WScript.Shell'))" & _
".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value)" & _
";close();<" & "/" & "script>"

但是,仍然没有工作。有没有办法使用此功能并自定义允许的文件类型?我只想允许.csv,.txt和.log

1 个答案:

答案 0 :(得分:1)

我在这里使用了这个功能:How to add filter to a file chooser in batch?

Function GetFileDlgEx(sIniDir,sFilter,sTitle) 
Set oDlg = CreateObject("WScript.Shell").Exec("mshta.exe ""about:<object id=d classid=clsid:3050f4e1-98b5-11cf-bb82-00aa00bdce0b></object><script>moveTo(0,-9999);eval(new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0).Read("&Len(sIniDir)+Len(sFilter)+Len(sTitle)+41&"));function window.onload(){var p=/[^\0]*/;new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).Write(p.exec(d.object.openfiledlg(iniDir,null,filter,title)));close();}</script><hta:application showintaskbar=no />""") 
oDlg.StdIn.Write "var iniDir='" & sIniDir & "';var filter='" & sFilter & "';var title='" & sTitle & "';" 
GetFileDlgEx = oDlg.StdOut.ReadAll 
End Function
set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
sIniDir = CurrentDirectory &"\Myfile.csv" 
sFilter = "csv files (*.csv)|*.csv|txt files (*.txt)|*.txt|log files (*.log)|*.log|" 
sTitle = "Put a title of your program here :) (-_°)" 
MyFile = GetFileDlgEx(Replace(sIniDir,"\","\\"),sFilter,sTitle) 
wscript.echo MyFile