LoginSignup
12
19

More than 3 years have passed since last update.

PowerShellでエクセルマクロを実行する

Last updated at Posted at 2019-09-27

PowerShellからExcelのVBAマクロを実行する。

:Run-ExcelMacro.ps1
Param(
    [string]$excel_file_name # マクロを実行するエクセルファイル名
    ,[string]$macro_name     # 実行するマクロ名
)

if( [String]::IsNullOrEmpty($excel_file_name) -or 
    [String]::IsNullOrEmpty($macro_name) ) {
    # 空のときは終わり
    Write-Host $excel_file_name is not found! 
    exit 1
}

if(Test-Path $excel_file_name) {
    $excel = New-Object -ComObject Excel.Application
    # Excelを表示しない
    $excel.Visible = $false
    $full_name = Convert-Path $excel_file_name
    $book = $excel.Workbooks.Open($full_name)
    $excel.run($macro_name)
    $book.close()
    $book = $null
    $excel.quit()
    $excel = $null
    [GC]::Collect()

    exit 0
}

Excelを非表示にしても、マクロ内のメッセージボックスは表示します。

Example

シート内のマクロは、シート名を付けて実行する。

PS C:\Work>.\Run-ExcelMacro.ps1 Test.xlsm Sheet1.TestMacro

GitHub

12
19
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
19