【Excel VBA】実行ログを残すマクロ

業務効率化
スポンサーリンク

複数のマクロを実行した際に、どのマクロがどのくらいの時間で終了したか気になることがあり作成しました。

自身の実行の時だけではなく、他の方が実行した際にログが欠けているとどのコードの手前で問題が起こったかというヒントにもなるため重宝しております。

実際のコード

  • 実行したスクリプト名を ログ!A:A に記入
  • 実行開始した時刻を ログ!B:B yyyy/mm/dd HH:MM 形式で記入
  • 終了した時刻を ログ!C:C yyyy/mm/dd HH:MM 形式で記入
  • いずれも、装飾が損なわれない方式で記入
Sub print_log()
    Dim wsLog As Worksheet
    Dim lastRowLog As Long
    Dim startTimeLog As Date
    Dim endTimeLog As Date
    Dim scriptNameLog As String
    
    ' ログ用シートを指定
    Set wsLog = ThisWorkbook.Sheets("ログ")
    
    ' スクリプト名(マクロ名を自動で取得)
    scriptNameLog = "テストのマクロ" '
    
    ' 開始時刻
    startTimeLog = Now
    
    ' 最終行を取得
    lastRowLog = wsLog.Cells(wsLog.Rows.Count, "A").End(xlUp).Row + 1
    
    ' ログ書き込み(書式を壊さないように Value のみ代入)
    wsLog.Cells(lastRowLog, 1).Value = scriptNameLog
    wsLog.Cells(lastRowLog, 2).Value = Format(startTimeLog, "yyyy/mm/dd HH:MM")
    
    ' ここでメイン処理を実行
    ' ------------------------------------------------
    MsgBox "処理。", vbInformation
    ' ------------------------------------------------
    
    ' 終了時刻
    endTimeLog = Now
    wsLog.Cells(lastRowLog, 3).Value = Format(endTimeLog, "yyyy/mm/dd HH:MM")
End Sub

いろんな人が使う場合の親切バージョン

追加した仕様は下記です。

  • ログ!D:D に所要時間を記入
  • 「ログ」という名称のシートがない場合はダイアログで『「ログ」シートが存在しないため作成して記入します。』と表示する。
  • 「ログ」という名称のシートがない場合は作成する
Sub print_log()
Dim wsLog As Worksheet
Dim lastRowLog As Long
Dim startTimeLog As Date
Dim endTimeLog As Date
Dim scriptNameLog As String
Dim elapsedTimeLog As String

' --- ログシートの存在確認 ---
On Error Resume Next
Set wsLog = ThisWorkbook.Sheets("ログ")
On Error GoTo 0

If wsLog Is Nothing Then
' シートが存在しない場合は作成
MsgBox "『ログ』シートが存在しないため作成して記入します。", vbInformation
Set wsLog = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsLog.Name = "ログ"

' ヘッダーを作成(初回のみ)
wsLog.Range("A1").Value = "スクリプト名"
wsLog.Range("B1").Value = "開始時刻"
wsLog.Range("C1").Value = "終了時刻"
wsLog.Range("D1").Value = "所要時間"
End If

' --- スクリプト名 ---
scriptNameLog = "テストのマクロ" ' 必要に応じて変更

' --- 開始時刻 ---
startTimeLog = Now

' --- 次の書き込み行 ---
lastRowLog = wsLog.Cells(wsLog.Rows.Count, "A").End(xlUp).Row + 1

' --- ログ書き込み(書式は壊さない) ---
wsLog.Cells(lastRowLog, 1).Value = scriptNameLog
wsLog.Cells(lastRowLog, 2).Value = Format(startTimeLog, "yyyy/mm/dd HH:MM")

' --- メイン処理 ---
MsgBox "処理。", vbInformation

' --- 終了時刻 ---
endTimeLog = Now
wsLog.Cells(lastRowLog, 3).Value = Format(endTimeLog, "yyyy/mm/dd HH:MM")

' --- 所要時間を計算(分+秒) ---
Dim totalSeconds As Long
totalSeconds = DateDiff("s", startTimeLog, endTimeLog)
elapsedTimeLog = Int(totalSeconds \ 60) & "分" & (totalSeconds Mod 60) & "秒"

wsLog.Cells(lastRowLog, 4).Value = elapsedTimeLog

MsgBox "処理が完了しました。", vbInformation
End Sub