【VBA】Run bat file

You can run “bat file”!

Use “Run method” of “WScript.Shell object“!

PR

VBA Code

For example, run following “batch file“:
*Show message.

@echo off

echo Hello! Run bat file! 

pause

rem Normal return code
exit /b 0

rem Error return code
rem exit /b 1
batch file
batch file

You can run “bat file” by “Run method” of “WScript.Shell object“.

Option Explicit

Sub sampleProc()

    Dim batchPath As String
    Dim wsh As Object
    Dim result As Integer
    
    'Set "bat file path"
    batchPath = "C:\Users\user\Desktop\sample.bat"
    
    Set wsh = CreateObject("WScript.Shell")
    
    'Run the "bat file"
    'Return
    '┗0 : Succeeded
    '┗1 : failed
    result = wsh.Run(batchPath, WaitOnReturn:=True)
    
    If (result = 0) Then
        MsgBox ("Succeeded")
    Else
        MsgBox ("failed ")
    End If
    
    Set wsh = Nothing
    
End Sub

Set “bat file path“(Line 10).

Run the “bat file“(Line 18).

If you want wait until the “bat file” finishes, set “WaitOnReturn” to “True“(Line 18).
*If not, set “WaitOnReturn” to “False”.

PR

Result

You ran “bat file“!

result①
result①
result②
result②
タイトルとURLをコピーしました