LoginSignup
4
3

More than 3 years have passed since last update.

いまさら PowerShell から VBA を実行させる

Last updated at Posted at 2021-05-05

PowerShell から VBA を実行させる

Windows&アプリインストールできない環境で機械的にExcelファイルを処理する必要がありなにかいい手段がないかなーと探してたときのメモ。忘れそうなので記事にしておきますw

PowerShell から Excel

いまどきExcelを操るのだったら「Python使えば!」ってなるのですが、PowerShell から COMインターフェースを使えば同じようなことができるらしい。しかも比較的簡単にできる。

セルの値を読む

やりたいことは、セルの値を読む。これだけ。
FinalReleaseComObject を指定しないとバックグランドでExcelが起動しっぱなしになるので気つけること。あとVSCodeで実行するとかならずバックグランドのExcelが終了しない。。。何故なんだろう。

image.png

read.ps1
$file = "read.xlsx"
$excel = $null

try {
    $excel = New-Object -ComObject Excel.Application
    $book = $excel.Workbooks.Open($file)
    $sheet = $book.ActiveSheet

    echo $sheet.Cells(1,2).Text
    echo $sheet.Cells(1,3).Text

    $book.Close()
} finally {
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel) | Out-Null
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($book) | Out-Null
}

実行してみる。

PS> powershell -NoProfile -ExecutionPolicy Unrestricted .\read.ps1

マクロの実行

Excel上のマクロを実行することも可能らしい。データを取り込んでピポットの更新&保存とかできるともうお手伝いさんいらず!!

macro.xlsm
Sub Hello()
  MsgBox "Hello, World!"
End Sub

のExcelマクロを PowerShell から呼び出してみる。

macro.ps1
$file = "macro.xlsm"
$excel = $null

try {
    $excel = New-Object -ComObject Excel.Application
    $book = $excel.Workbooks.Open($file)

#    $target = "Module1.Hello"   # こっちでもいける
    $target = "Hello"
    $excel.Run($target)

    $book.Close()
} finally {
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel) | Out-Null
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($book) | Out-Null
}

実行してみる。

PS> powershell -NoProfile -ExecutionPolicy Unrestricted .\macro.ps1

以外と手法はある

これぐらいの簡単なことでもJava至高という考えでなければ、色々と手段がありますね。

参考

PowerShell から Excel を操作(オートメーション)
Windows PowerShell を使って Excel を操作する – セル操作編 vol.1
OfficeアプリのコントロールはPowerShellかVBAか?

4
3
0

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
4
3