【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]SaveAs名前を付けて保存 【VBA】名前を付けて保存|SaveAs -

[VBA]Control the calculation再計算 【VBA】指定のシートを再計算する|Calculate -

[VBA]Log WriterLet’s log this. 【VBA】ログをファイル出力するクラス|LogWriter -

テーブルの値を取得する 【VBA】Excelテーブルのデータを配列で取得する -

[VBA]openbook 【VBA】ブックを開く|OpenBook -

dictionaryをセットする 【VBA】Dictionaryのセット|CreateObject(“Scripting.Dictionary”)