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

后端 未结 9 1800
野性不改
野性不改 2020-12-03 07:50

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 = Creat         


        
9条回答
  •  无人及你
    2020-12-03 08:12

    If you have some degree of control over the systems on which you'll be deploying this, and can be reasonably certain that they have either Visual Studio or Microsoft HTML Help installed, you can use code like the following:

    function filedialog(filt, def, title, save)
        set dialog = CreateObject("MSComDlg.CommonDialog")
        dialog.MaxFileSize = 256
        if filt = "" then
            dialog.Filter = "All Files (*.*)|*.*"
        else
            dialog.Filter = filt
        end if
        dialog.FilterIndex = 1
        dialog.DialogTitle = title
        dialog.InitDir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments")
        dialog.FileName = ""
        if save = true then
            dialog.DefaultExt = def
            dialog.Flags = &H800 + &H4
            discard = dialog.ShowSave()
        else
            dialog.Flags = &H1000 + &H4 + &H800
            discard = dialog.ShowOpen()
        end if
        filedialog = dialog.FileName
    end function
    

    Also, adapting one of the other answers to this question into VBScript code (thanks @oddacorn!), you should add this function if you aren't reasonably certain that your users will have VS or HTML Help. Call this function on program startup. Don't worry if you already have the key; in that case, this has no effect. This should work on a standard user account without admin rights.

    'Make the MSComDlg.CommonDialog class available for use. Required for filedialog function.
    function registerComDlg
        Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv")
        objRegistry.CreateKey &H80000001, "Software\CLASSES\Licenses\4D553650-6ABE-11cf-8ADB-00AA00C00905"
        objRegistry.SetStringValue &H80000001, "Software\CLASSES\Licenses\4D553650-6ABE-11cf-8ADB-00AA00C00905", "", "gfjmrfkfifkmkfffrlmmgmhmnlulkmfmqkqj"
    end function
    

    Note that I adapted the filedialog function from the "View Source" of the VBScript code in the HTML here; on modern web browsers, it appears that the HTML they use to render the code samples doesn't display correctly (tested on IE 8 and Chrome). But fortunately the code is still there in the View Source.

    I found one thing that was critical to making this work on Windows 7 (SP1, fully patched); you must set dialog.MaxFileSize = 256 or you will get a run-time error.

    That is, the following code fails on Windows 7 SP1, but probably works on older versions of Windows:

    Set x = CreateObject("MSComDlg.CommonDialog")
    x.ShowSave
    

提交回复
热议问题