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

Excel VBA VBA
スポンサーリンク

業務でよく使う 「安全に動く」「再利用できる」テンプレートコード集 をまとめました。ログ出力やエラー処理を組み込んでいるので、実務ですぐ活用できます。


1. 基本構造(ログ+エラー処理付き)

Option Explicit

'=== ログ出力 ===
Sub WriteLog(msg As String)
    Dim ws As Worksheet
    Dim lastRow As Long
    
    On Error Resume Next
    Set ws = ThisWorkbook.Sheets("Log")
    If ws Is Nothing Then
        Set ws = ThisWorkbook.Sheets.Add
        ws.Name = "Log"
    End If
    On Error GoTo 0
    
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row + 1
    ws.Cells(lastRow, 1).Value = Now
    ws.Cells(lastRow, 2).Value = msg
End Sub

'=== メイン処理 ===
Sub MainProcess()
    On Error GoTo ErrHandler
    
    WriteLog "処理開始"
    
    ' ▼ここに業務処理を書く
    Range("A1").Value = "Hello VBA!"
    
    WriteLog "処理正常終了"
    Exit Sub
    
ErrHandler:
    WriteLog "エラー発生: " & Err.Number & " - " & Err.Description
    MsgBox "エラーが発生しました。ログを確認してください。", vbCritical
End Sub
VB

2. データ集計テンプレ

Sub SumColumn()
    On Error GoTo ErrHandler
    WriteLog "集計開始"
    
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim total As Double
    
    Set ws = ThisWorkbook.Sheets("Data")
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    
    total = Application.WorksheetFunction.Sum(ws.Range("A2:A" & lastRow))
    ws.Range("B1").Value = "合計"
    ws.Range("B2").Value = total
    
    WriteLog "集計完了"
    Exit Sub
    
ErrHandler:
    WriteLog "集計エラー: " & Err.Description
End Sub
VB

3. ファイル処理テンプレ

Sub ExportCSV()
    On Error GoTo ErrHandler
    WriteLog "CSV出力開始"
    
    Dim ws As Worksheet
    Dim filePath As String
    
    Set ws = ThisWorkbook.Sheets("Data")
    filePath = ThisWorkbook.Path & "\export.csv"
    
    ws.Copy
    ActiveWorkbook.SaveAs Filename:=filePath, FileFormat:=xlCSV
    ActiveWorkbook.Close False
    
    WriteLog "CSV出力完了: " & filePath
    Exit Sub
    
ErrHandler:
    WriteLog "CSV出力エラー: " & Err.Description
End Sub
VB

4. ユーザー入力チェックテンプレ

Function IsValidInput(value As Variant) As Boolean
    If IsNumeric(value) Then
        If value >= 0 Then
            IsValidInput = True
        Else
            IsValidInput = False
        End If
    Else
        IsValidInput = False
    End If
End Function

Sub TestInput()
    Dim inputValue As Variant
    inputValue = Range("A1").Value
    
    If IsValidInput(inputValue) Then
        MsgBox "入力は有効です"
    Else
        MsgBox "入力が不正です"
    End If
End Sub
VB

実務での使い方

  • ログ付きテンプレ → すべての業務処理の「開始」「終了」「エラー」を記録
  • 集計テンプレ → データシートの合計や平均を自動計算
  • ファイル処理テンプレ → CSVやTXTへの出力を安全に実行
  • 入力チェックテンプレ → ユーザー入力の妥当性を確認

✅ まとめ

  • Sub:処理を実行する
  • Function:結果を返す
  • ログ+エラー処理を組み込むことで、業務マクロが「安全・追跡可能」になる
タイトルとURLをコピーしました