How can I use the common Save As dialog from VBScript?

JayK picture JayK · Dec 8, 2010 · Viewed 30.6k times · Source

I'd like to have my VBScript display the Windows Save As dialog box, but I could not find out how to do it.

Using this code:

Dim sfd
Set sfd = CreateObject("UserAccounts.CommonDialog")
sfd.ShowOpen

I can get an Open dialog, but there is no ShowSave method for this object (as there seems to be for a similar object in Visual Basic non-script).

I searched StackOverflow and googled for "[vbscript] save dialog" (and with "Windows Script Host"), but I only found threads about accessing common dialogs from web pages and a solution for the BrowseForFolder dialog and nothing really about calling the Save dialog.

Actually, I can use the Open dialog for my purpose, because all I need is a file name... but as I'd like to save something to the selected path, a "Save As" in the title bar of the dialog would be more appropriate.

Answer

oddacorn picture oddacorn · Dec 16, 2010

The secret to using the common dialog from VBScript (or VBA or JScript, for that matter) is that you have to have its license installed on your machine. Certain development tools, such as Visual Basic 6, will install the license, but it's also installed by the free Microsoft HTML Help Editor (this is a pretty old app). The interesting thing is that if you install and then uninstall the HTML Help Editor, it leaves the Common Dialog License in place. For this reason I would consider the license to be freely available and so will include the registry entry it creates here in my answer:

In HKLM\Software\CLASSES\Licenses\4D553650-6ABE-11cf-8ADB-00AA00C00905, set the (Default) entry to gfjmrfkfifkmkfffrlmmgmhmnlulkmfmqkqj.

Once that's in place, you can create these dialogs from within a VBScript using code like this:

Set objDialog = CreateObject("MSComDlg.CommonDialog")

To launch a file save dialog, use the ShowSave method as in this code:

objDialog.ShowSave

Of course this object has a bunch of other methods and properties, and you'll probably want to configure the appropriate properties before launching the dialog. For example, you can set the file filter so only certain file extensions are shown in the dialog. There's a nice reference to the control on the MSDN site here: http://msdn.microsoft.com/en-us/library/aa259661%28v=vs.60%29.aspx.

Hope this helps. Let me know if you have any questions.