我在 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
最佳答案
我在这里使用了这个函数: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
关于function - VBScript BrowseForFile() 函数 - 如何指定文件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38643487/