【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】ユーザーフォームのタイトルバーを非表示にしてシステムっぽい見た目にする -

[VBA]開いているかwith FullName 【VBA】ブックが開いているか判定|StrComp で FullNameを調べる -

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

[VBA]StrCompで文字列比較 【VBA】拡張子の存在確認|Right + StrComp -

Excelでメール作成とOutlook起動 【VBA】Excelでメール内容を作成してOutlookを起動する -

vbaの色設定 【VBA】色の定数は8つ|RGB対称表