VBScript to open a dialog to select a filepath
Asked Answered
C

5

12

At present I am opening a file with my vbscript as follows:

strFile = "C:\Users\test\file.txt"
Set objFile = objFSO.OpenTextFile(strFile)

I would like to change this so that a file can be selected/navigated to by the user and that file is used in the script. How can I add this ability? I have tried to search for how to load a file dialog/prompt the user for a file etc just not sure how to complete in a VBScript.

Claudell answered 4/2, 2014 at 17:52 Comment(0)
S
34

There is another solution I found interesting from MS TechNet less customization but gets what you wanted to achieve. This returns the full path of the selected file.

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>""")
sFileSelected = oExec.StdOut.ReadLine
wscript.echo sFileSelected
Scatter answered 4/2, 2014 at 23:51 Comment(7)
Thanks. Tested successfully on 64-bit Windows 10 Pro.Hum
I like this solution, is it possible to set a filter to a filetype (i.e. *.txt)?Cordage
@Cordage This Old SO post may help you.Scatter
@Cordage Somehow, I don't like it. It seems kinda hacky that you need to do it this way. All other VBS solutions I've come across use a weird version that isn't provided by the windows explorer to pick a file. But since it is just HTML, you would filter out any file like you would in a HTML document.Archbishop
Nice. Here is a commented function based on the same code: robvanderwoude.com/vbstech_ui_fileopen.php#ExecMSHTAGrasping
@Cordage - it's not pure HTML but hta, so in theory it was supposed to be possible to use accept=".filetype" inside <input type="file"> but hta completely ignores it. I've therefore added an alternative answer, which is similar to the "old SO post" but with some added values like relative folders. @StuartM, please consider it.Informant
tried in my hta file and it complained unterminated string. Had to use Chr(39) to replace the single quote character and Chr(47) to replace the slash (/) character to make it workPenstock
M
2

Here you go:

http://www.robvanderwoude.com/vbstech_ui_fileopen.php

strFile = GetFileName("C:\Users\test\", "Text files|*.txt")
Set objFile = objFSO.OpenTextFile(strFile)

Function GetFileName( myDir, myFilter )
  ' Written by Rob van der Woude
  ' http://www.robvanderwoude.com

  ' Standard housekeeping
  Dim objDialog

  ' Create a dialog object
  Set objDialog = CreateObject( "UserAccounts.CommonDialog" )

  ' Check arguments and use defaults when necessary
  If myDir = "" Then
    ' Default initial folder is "My Documents"
    objDialog.InitialDir = CreateObject( "WScript.Shell" ).SpecialFolders( "MyDocuments" )
  Else
    ' Use the specified initial folder
    objDialog.InitialDir = myDir
  End If
  If myFilter = "" Then
    ' Default file filter is "All files"
    objDialog.Filter = "All files|*.*"
  Else
    ' Use the specified file filter
    objDialog.Filter = myFilter
  End If

  ' Open the dialog and return the selected file name
  If objDialog.ShowOpen Then
    GetFileName = objDialog.FileName
  Else
    GetFileName = ""
  End If
End Function
Marchelle answered 4/2, 2014 at 18:21 Comment(1)
Helps to test, or at least mention the caveat that UserAccounts.CommonDialog is unavailable on any 64-bit host.Justinajustine
I
1

The currently chosen answer doesn't support filters, but hta can be manipulated to support them. Here's an answer based on this tek-tips.com post (which is also mentioned in How to add filter to a file chooser in batch?), but I added a full function structure plus support for relative folders:

Function GetFileDlgEx(sIniDir,sFilter)
  sTitle = "Choose File"
  set objShell = WScript.CreateObject("WScript.Shell")
  if instr(sIniDir, ":") <= 0 then
    sIniDir = objShell.CurrentDirectory & "\" & sIniDir
  end if
  sIniDir = Replace(sIniDir,"\","\\")
  Set oDlg = objShell.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

sIniDir = "*.*pdf" ' will look in current folder - note extension must be preceded by an asterisk *.
'sIniDir = "docs\*.*pdf" ' will look in a relative folder
'sIniDir = "C:\Windows\*.*pdf" ' will look in an absolute folder
sFilter = "Adobe pdf (*.pdf)|*.pdf|All files (*.*)|*.*|Microsoft Word (*.doc;*.docx)|*.doc;*.docx|Image files (*.gif;*.png;*jpg;*.bmp)|*.gif;*.png;*jpg;*.bmp|Html files (*.htm;*.html;*.mht)|*.htm;*.html;*.mht|"
rep = GetFileDlgEx(sIniDir,sFilter)
MsgBox rep
Informant answered 14/1, 2023 at 13:30 Comment(0)
D
0

VBSEdit program installs a COM library VBSEdit Toolkit, which allows Open File dialogs.

From VBSEdit help:

Dialog boxes 
OpenFileDialog method
Prompt the user to open a file
toolkit.OpenFileDialog ([initialFolder,[filters,[multiselect,[title]]]]) 

'Opens a single file
Set toolkit = CreateObject("VbsEdit.Toolkit")
files=toolkit.OpenFileDialog("c:\scripts\","Text Files (*.txt)|*.txt",False,"Open a text file")
If UBound(files)>=0 Then
  WScript.Echo files(0)
Else
  Wscript.Quit
End If

'Opens multiple files
Set toolkit = CreateObject("VbsEdit.Toolkit")
files=toolkit.OpenFileDialog("c:\scripts\","Text Files (*.txt)|*.txt",True,"Open a text file")
If UBound(files)>=0 Then
  For Each filepath In files
    WScript.Echo filepath
  Next
Else
  Wscript.Quit
End If



SaveFileDialog method
Prompt the user to save a file
toolkit.SaveFileDialog ([initialFolder,[initialFilename,[filters,[title]]]]) 

Set toolkit = CreateObject("VbsEdit.Toolkit")
filepath = toolkit.SaveFileDialog("c:\scripts","test.txt","Text Files (*.txt)|*.txt")

If Not(IsNull(filepath)) Then
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFile = objFSO.CreateTextFile(filepath,True)
  objFile.WriteLine Date
  objFile.Close
Else
  Wscript.Quit
End If



SelectFolder method
Prompt the user to select a folder
toolkit.SelectFolder ([initialDir,[title]]) 

Set toolkit = CreateObject("VbsEdit.Toolkit")
myfolder=toolkit.SelectFolder("c:\scripts\","Please select a folder")

If Not(IsNull(myfolder)) Then
  WScript.Echo myfolder
Else
  Wscript.Quit
End If

(Actually, folder selection dialogs can be opened without VBSEdit toolkit, with BrowseForFolder method of Shell.Application object.)

Dentation answered 7/3, 2019 at 12:40 Comment(0)
S
0

Found this answer HERE

Set WshShell=CreateObject("Wscript.Shell")

WshShell.BrowseForFolder(0, "Please select the folder.", 1, "")
Smaragdine answered 21/2, 2023 at 23:29 Comment(2)
should be: Set WshShell = CreateObject( "Shell.Application" )Penstock
Although you can display files with .BrowseForFolder, the method will only return a folder.Rothberg

© 2022 - 2024 — McMap. All rights reserved.