やり方
まず『コマンドプロンプトを使う為のクラス』が使えるように参照設定。
Windows Script Host Object Model
サンプルコード
'コマンドプロンプトを使う為のクラス。
Dim wsh_shell_ As New IWshRuntimeLibrary.WshShell
'実行結果保持用。
Dim shell_result_ As IWshRuntimeLibrary.WshExec
'フォルダーを作成するコマンド。
Dim command_ As String
command_ = "mkdir C:\Users\d\Desktop\bat\test"
'コマンド実行して結果を保持。
Set shell_result_ = wsh_shell_.Exec("%ComSpec% /c " & command_)
'結果確認。
Debug.Print shell_result_.ExitCode
Run()
WshShellには Run()
という関数もある。
関数名 | コマンドプロンプト画面 | コマンド実行結果取得 |
---|---|---|
Run() | 表示されない | できない |
Exec() | 表示される | できる |
蛇足
『もしコマンドが失敗したらユーザーに通知 or メール通知 or ログ出力』
という要件が後から追加されることがある。
個人的には最初からExec()で作っておいた方がいいかなあって思う。
参考サイトさん
バージョン
Windows 10 Pro 21H2 OSビルド 19045.2251
Microsoft Access for Microsoft 365 MSO (バージョン 2209 ビルド 16.0.15726.20068) 32 ビット