Satyavan Choure
Satyavan Choure

Reputation: 99

Exit Cmd window after execution of script in VBA

I would like to Exit the CMD window after execution of script (currently I am exiting CMD manually by writing exit in the CMD window, after which VBA continues running)

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 Long
errorCode = wsh.Run(sCmdline, windowStyle, waitOnReturn)

'-- Finally Run function Arguments ----- 
 errorCode = wsh.Run("cmd /k systeminfo >D:\Tools\MyScript\SystemInfo.txt", windowStyle, waitOnReturn)

If errorCode = 0 Then
    MsgBox "Done! No error to report."
    Set wsh = Nothing
Else
    MsgBox "Program exited with error code " & errorCode & "."
    Set wsh = Nothing
End If

Upvotes: 1

Views: 3100

Answers (2)

double-beep
double-beep

Reputation: 5519

You seem to want to close the cmd after you open it. /C flag is the best here, because it carries out the command specified by string and then terminates.

So, you should write:

errorCode = wsh.Run("cmd /c systeminfo >D:\Tools\MyScript\SystemInfo.txt", windowStyle, waitOnReturn)

which will work.

Upvotes: 1

Matteo NNZ
Matteo NNZ

Reputation: 12695

In your sCmdLine (which is not defined in your question), just add && exit at the end to execute the commands one after the other in a single line.

If your original command was sCmdLine = "cmd.exe /S /K ping www.google.com", then it would become sCmdLine = "cmd.exe /S /K ping www.google.com && exit".

Upvotes: 1

Related Questions