LoginSignup
7
13

More than 3 years have passed since last update.

Excel の WorkSheets を PowerShell で扱うと楽になる

Last updated at Posted at 2017-08-15

VBA だと worksheets を走査するのにいちいち For したりするので面倒ですよね?

PowerShell なら1行でヤレます。

デフォルトで追加されるSheet1,Sheet2,Sheet3とか全部消す
$Excel = New-Object -com Excel.Application
$Book = $Excel.WorkBooks.Open($BookPath)
$Book.WorkSheets | ? { $_.Name -match "Sheet[0-9]*" } | % { $_.Delete() } # 1行!
$Book.Save()
$Book.Close($False)
$Exce.Quit()

ただし、広い範囲の Range とかだと読み出しに時間がかかるので遅くなります。

値の入っているセルの数をカウントしようとする
$Excel = New-Object -com Excel.Application
$Book = $Excel.WorkBooks.Open($BookPath)
$Sheet = $Book.WorkSheets | Select -First 1
$Sheet.Range("A1:Z1000") | ? { $_.Text } | measure # 遅い

基本的に PowerShell の方が構文が綺麗なので使いたいんですが、VBA の方が実行速度が出やすいんですよね。

使い所~

7
13
4

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
7
13