LoginSignup
1
5

More than 5 years have passed since last update.

[VBScript] ドロップされたExcelファイルのシート名を全て取得してファイルに出力

Last updated at Posted at 2017-09-20

2017年にもなってVBScriptもどうなんだとは思いますが、こういうExcelのちょっとした操作にはPythonとかよりもジッサイ便利なので・・・。

使い方

適当な場所に GetExcelSheetNames.vbs のようなファイルを作成して、そのファイルに対して対象のエクセルファイル(複数同時可)をドロップすれば良いです。"hoge.xlsx" とかなら "hoge_sheets.txt" のような名前でスクリプトと同じディレクトリに出力されます。

だいぶレガシーなコードですが Windows10 + Excel2016 でも問題なく動くかと思います。

実装

GetExcelSheetNames.vbs
Set book = CreateObject("Excel.Application")
book.Visible = False

Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

Dim currentDir
currentDir = fso.getParentFolderName(WScript.ScriptFullName)

For Each strFname In WScript.Arguments
    Set objDoc = book.Workbooks.Open(strFname)

    Dim fileBaseName, outputFilePath
    fileBaseName = fso.GetBaseName(strFname)
    outputFilePath = currentDir & "\" & fileBaseName & "_sheetlist.txt"

    Dim outputFile
    Set outputFile = fso.OpenTextFile(outputFilePath, 2, True)

    For Each sheet In objDoc.Sheets
        outputFile.WriteLine sheet.Name
    Next

    objDoc.Close
    Set objDoc = Nothing
Next

book.Quit
Set book = Nothing

outputFile.Close
Set outputFile = Nothing

Set WshShell = Nothing
Set fso = Nothing
Set book = Nothing

参考

WSHでスクリプトファイル自身が存在するフォルダパスを取得する - Qiita

1
5
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
1
5