【VBA】Run command(Command Prompt)

You can run “command”!
*Command Prompt.

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

PR

VBA Code

For example, run following “command“:
*Create folder001.

mkdir C:\Users\user\Desktop\folder001


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

Option Explicit

Sub sampleProc()

    Dim command As String
    Dim wsh As Object
    Dim result As Integer
    
    'Set "command"
    command = "mkdir C:\Users\user\Desktop\folder001"
    
    Set wsh = CreateObject("WScript.Shell")
    
    'Run the "command"
    'Return
    '┗0 : Succeeded
    '┗1 : failed
    result = wsh.Run("%ComSpec% /c " & command, WindowStyle:=0, WaitOnReturn:=True)
    
    If (result = 0) Then
        MsgBox ("Succeeded Run command.")
    Else
        MsgBox ("failed Run command.")
    End If
    
    Set wsh = Nothing
    
End Sub

Set “command“(Line 10).

Run the “command“(Line 18).

Detail “Run the command“(Line 18):

%ComSpec%“・・・Command Prompt exe file path.
/c“・・・C drive.
WindowStyle“・・・If you Hide Command Prompt screen, Set “0”.
WaitOnReturn“・・・If you wait until the “command” finishes, Set “True”.

%ComSpec%” equals “C:\WINDOWS\system32\cmd.exe“.

Detail "%ComSpec%"
Detail “%ComSpec%
PR

Result

You ran “command(Command Prompt)“!
*Created folder001.

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