📊 Excel VBA Top100
🔧

LogToSheet

ユーティリティ

ログメッセージをシートに書き込む

🎬 デモGIF準備中

📖 使い方

  1. VBAエディタを開く(Alt + F11)
  2. モジュールを挿入(挿入 > モジュール)
  3. 下記VBAコードをコピー&ペースト
  4. ブック上で実行(Alt + F8 でマクロ選択)
💡 実行例: 実行するとログシートにタイムスタンプ付きでメッセージが記録される

💻 VBAコード

' LogToSheet
' -----------------
' Macro Name: LogToSheet
' Description: ログメッセージをシートに書き込む
' Parameters: なし
' Returns: なし
' Usage: 実行するとログシートにタイムスタンプ付きでメッセージが記録される
' -----------------

Sub LogToSheet()
    Dim ws As Worksheet
    Dim logMsg As String
    Dim logLevel As String
    Dim outputRow As Long
    Dim lastRow As Long

    On Error GoTo ErrorHandler

    logLevel = InputBox("ログレベルを選択:" & vbCrLf & _
                "1: INFO" & vbCrLf & _
                "2: WARNING" & vbCrLf & _
                "3: ERROR" & vbCrLf & _
                "4: DEBUG", "ログ記録", "1")

    If logLevel = "" Then
        Exit Sub
    End If

    logMsg = InputBox("ログメッセージを入力:", "ログ記録")

    If logMsg = "" Then
        MsgBox "メッセージが空です。", vbInformation
        Exit Sub
    End If

    Select Case logLevel
        Case "1": logLevel = "INFO"
        Case "2": logLevel = "WARN"
        Case "3": logLevel = "ERROR"
        Case "4": logLevel = "DEBUG"
        Case Else: logLevel = "INFO"
    End Select

    On Error Resume Next
    Set ws = Worksheets("ログ")
    On Error GoTo ErrorHandler

    If ws Is Nothing Then
        Set ws = Worksheets.Add(Before:=Worksheets(1))
        ws.Name = "ログ"
        ws.Cells(1, 1).Value = "日時"
        ws.Cells(1, 2).Value = "レベル"
        ws.Cells(1, 3).Value = "メッセージ"
        ws.Cells(1, 1).Font.Bold = True
        ws.Cells(1, 2).Font.Bold = True
        ws.Cells(1, 3).Font.Bold = True
        ws.Range(ws.Cells(1, 1), ws.Cells(1, 3)).Interior.Color = RGB(200, 200, 200)
    End If

    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    outputRow = lastRow + 1

    ws.Cells(outputRow, 1).Value = Now
    ws.Cells(outputRow, 1).NumberFormat = "yyyy/mm/dd hh:nn:ss"
    ws.Cells(outputRow, 2).Value = logLevel
    ws.Cells(outputRow, 3).Value = logMsg

    Select Case logLevel
        Case "WARN": ws.Cells(outputRow, 2).Interior.Color = RGB(255, 255, 0)
        Case "ERROR": ws.Cells(outputRow, 2).Interior.Color = RGB(255, 100, 100)
        Case "DEBUG": ws.Cells(outputRow, 2).Interior.Color = RGB(200, 200, 200)
    End Select

    ws.Columns("A:C").AutoFit
    MsgBox "ログを記録しました。", vbInformation
    Exit Sub

ErrorHandler:
    MsgBox "エラーが発生しました: " & Err.Description, vbCritical
End Sub