vba WScript.Shell run .exe file with parameter
Asked Answered
S

2

5

I am running a VBA macro from Word 2013. I'm trying to run an executable file which requires an argument/parameter of a filename. For example, c:\myfilefilter.exe filetobefiltered.htm

I would like to use Shell Run because I want the VBA code to wait until the executable is finished running before resuming the VBA code. The last three lines in the code below are examples of some of the syntax I have tried which do not work. I think the problem is the space between the executable program and the file it filters. Does anybody know the correct syntax or a way to wait for the executable program to finish. If you need more info, please ask.

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
Dim strProgramName As String
Dim strMyFile As String
Call Shell("""" & strProgramName & """ """ & strMyFile & """", vbNormalFocus, waitOnReturn"""")
wsh.Run(strProgramName & """ """ & fileToFilterB & """", vbNormalFocus, waitOnReturn)
wsh.Run "Chr(34)strProgramNameChr(34)strMyFile", waitOnReturn

The code below works. After strCMD, the first number is a boolean argument: 1 displays the dos box and 0 hides the dos box; the second number is similar: 1 waits for the program to finish before continuing the VBA code, 0 does not wait.

strCMD = sMyProgram + " " + sMyFile
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
wsh.Run strCMD, 1, 1
Spock answered 5/11, 2014 at 16:46 Comment(1)
I don't know the answer and don't have a good way to test, but in your last line you should remove all of the quotation marks and join Chr(34) and your variables with ampersands. I assume you're defining all these variable somewhere?Pneumatograph
S
10

You could try this. Works for me.

Const BatchFileName = "P:\Export.bat"

Dim wsh As Object

Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run BatchFileName, windowStyle, waitOnReturn

Kill BatchFileName
Selmaselman answered 1/12, 2015 at 4:17 Comment(0)
N
7

this works for me (from MsAccess 2013 VBA)

Dim wShell As New WshShell
Dim wsExec As WshExec
    Dim cmdline As String
    cmdline = "notepad c:\somefile.txt"
    Debug.Print Now, cmdline
    Set wsExec = wShell.Exec(cmdline)
    Do While wsExec.Status = 0
        DoEvents
    Loop
    Debug.Print Now, "done"
Noeminoesis answered 9/5, 2015 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.