Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBScript to open a dialog to select a filepath

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.

like image 844
StuartM Avatar asked Feb 04 '14 17:02

StuartM


2 Answers

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
like image 110
PatricK Avatar answered Sep 22 '22 10:09

PatricK


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
like image 38
Nathan Rice Avatar answered Sep 19 '22 10:09

Nathan Rice