Excel VBA | 実務用 VBA コード集(テンプレ付き)

Excel VBA VBA
スポンサーリンク

Windowsタスクスケジューラと連携して完全自動実行(Excelを開かなくても動く)版

Excel VBAは通常「ブックを開いたとき」にしか動きませんが、Windowsタスクスケジューラを使えば「Excelを開かなくても自動実行」できます。ポイントは VBAマクロを含むExcelファイルをコマンドラインで起動し、指定のマクロを実行する ことです。


手順概要

  1. 実行したいマクロを作成
    • 例:Sub AutoRun() を作り、ログ圧縮や処理を記述する
  2. Excelファイルを保存
    • 例:C:\Scripts\LogManager.xlsm
  3. タスクスケジューラで新規タスクを作成
    • トリガー:毎月1日 午前9時
    • 操作:Excel.exe を呼び出し、対象ファイルとマクロを指定

VBA側のコード例

Option Explicit

'=== 自動実行マクロ ===
Sub AutoRun()
    ' ここに月初処理(ログ圧縮など)を書く
    Call ZipArchiveLogs
End Sub

'=== ZIP圧縮処理(前回のコードを利用) ===
Sub ZipArchiveLogs()
    Dim fso As Object, folder As Object, file As Object
    Dim archivePath As String, zipFilePath As String
    
    archivePath = ThisWorkbook.Path & "\Archive"
    zipFilePath = ThisWorkbook.Path & "\ArchiveLogs_" & Format(Date, "yyyymm") & ".zip"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FolderExists(archivePath) Then Exit Sub
    
    If fso.FileExists(zipFilePath) Then fso.DeleteFile zipFilePath
    
    ' 空ZIP作成
    Open zipFilePath For Output As #1
    Print #1, "PK" & Chr(5) & Chr(6) & String(18, vbNullChar)
    Close #1
    
    ' ShellでZIPにファイルをコピー
    Dim sh As Object, zipFolder As Object
    Set sh = CreateObject("Shell.Application")
    Set zipFolder = sh.NameSpace(zipFilePath)
    
    Set folder = fso.GetFolder(archivePath)
    For Each file In folder.Files
        zipFolder.CopyHere file.Path
        Application.Wait (Now + TimeValue("0:00:01"))
    Next file
End Sub
VB

タスクスケジューラ設定例

  1. 操作 → 新しいタスクの作成
    • 名前:Excel Log Manager
    • トリガー:毎月1日 午前9:00
    • 操作:プログラムの開始
  2. 操作の詳細
    • プログラム/スクリプト: "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" (Excelの場所は環境によって異なる)
    • 引数の追加: "C:\Scripts\LogManager.xlsm" /m AutoRun/m AutoRun で指定マクロを実行

実務でのメリット

  • Excelを開かなくても自動実行
  • 月初に確実に処理が走る
  • ログ圧縮や定期処理を完全自動化

✅ まとめ

  • VBA側で「AutoRun」マクロを用意
  • タスクスケジューラで「Excel.exe + ファイル + マクロ」を指定
  • 毎月の定期処理を完全自動化できる
タイトルとURLをコピーしました