【VBA】指定場所にあるPowerShellスクリプトを実行する
作成日:2025-11-02
更新日:2025-11-02

短いスクリプトなら、VBAに直書き
長いスクリプトは直書きができないため、呼び出して実行する
ExcelからPowerShellスクリプトを呼び出すテスト用コード
Public Sub RunScript()
Dim ws As Worksheet
Dim scriptPath As String
Dim targetPath As String
Dim shellCommand As String
' 末尾のバックスラッシュを調整
Dim basePath As String
basePath = ThisWorkbook.Path
If Right(basePath, 1) <> "¥" Then basePath = basePath & "¥"
scriptPath = basePath & "list.ps1"
' ターゲットパスの選択
#If USE_TEST_PATH Then
targetPath = Left(TEST_PATH_OUTPUT, Len(TEST_PATH_OUTPUT) - 1)
#Else
targetPath = "(指定のパス)"
#End If
' PowerShellコマンドを構築
shellCommand = "powershell.exe -ExecutionPolicy Bypass -File """ & scriptPath & _
""" -Path """ & targetPath & """"
' 完了まで待機して実行
CreateObject("WScript.Shell").Run shellCommand, 1, True
End Sub目的
このSubは、ExcelからPowerShellスクリプトを呼び出すためのテスト用ランチャー。list.ps1 を実行し、引数として -Path に指定フォルダを渡す仕組み。
Vocabulary
| 英語 | 日本語 |
|---|---|
| ExecutionPolicy | 実行ポリシー |
| Bypass | 制限回避モード |
| Chr(34) | 二重引用符の文字コード |
| Shell Function | シェル関数 |
| WScript.Shell | Windowsスクリプトホストオブジェクト |
| Wait for completion | 完了待機 |
| Safe path concatenation | 安全なパス結合 |
外部スクリプト実行時は常に安全性を意識すること。
2025-11-02
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[VBA]Resizerows and columns 【VBA】Resize changes the size of a cell range|範囲のリサイズ -

[VBA]ShowMessage Box 【VBA】メッセージボックスをモジュールに集める|OKOnly,OKCancel,YesNo -

数値に+ 記号を追加 【VBA】正の数値に+記号を追加|Sgn -

[VBA]InStr文字列確認 【VBA】指定の文字列が含まれているか & 前後の文字列を返す|InStr/InStrRev -

絶対値を取得 【VBA】絶対値を取得する|Abs -

ユーザーフォームをシステムっぽく 【VBA】ユーザーフォームのみ起動して、シートを表示しない方法