では、フル Excel ファイル版の実務マクロテンプレ集として構成します。
ポイントは以下です:
ファイル構成(Excel + VBA モジュール)
1. シート構成
| シート名 | 目的 |
|---|---|
| ログ | ログ記録用(日時 + メッセージ) |
| データ | CSVやDB読み込み用のデータ貼り付け用 |
| 設定 | 外部ファイルパスやメールアドレスなどの設定を管理 |
| テスト | 各サンプル Sub の動作確認用 |
2. VBA モジュール構成
| モジュール名 | 内容 |
|---|---|
| Module1_Common | 文字列/数値/配列処理、汎用関数 |
| Module2_Data | CSV 読み込み、配列→シート書き込み Sub |
| Module3_LogError | ログ記録 Sub、SafeRun(エラー処理共通化) |
| Module4_Outlook | Outlook メール送信 Sub |
| Module5_ADO | DB 接続・データ取得関数 |
| Module6_Test | 各 Sub のテスト用マクロ |
3. モジュール例(要点抜粋)
Module1_Common
Function Round2(val As Double, Optional digits As Long = 2) As Double
Round2 = WorksheetFunction.Round(val, digits)
End Function
Function JoinArray(arr As Variant) As String
JoinArray = Join(arr, ", ")
End Function
Function IsEmptyCell(rng As Range) As Boolean
IsEmptyCell = Trim(rng.Value) = ""
End Function
VBModule3_LogError
Sub LogWrite(msg As String)
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("ログ")
Dim nextRow As Long
nextRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row + 1
sh.Cells(nextRow, 1).Value = Now
sh.Cells(nextRow, 2).Value = msg
End Sub
Sub SafeRun(target As String)
On Error GoTo ErrHandler
Application.ScreenUpdating = False
CallByName Me, target, VbMethod
ExitPoint:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
LogWrite "Error in " & target & ": " & Err.Number & " - " & Err.Description
Resume ExitPoint
End Sub
VBModule4_Outlook
Sub SendMail(toAddr As String, subject As String, bodyText As String, Optional attachPath As String)
On Error GoTo ErrHandler
Dim olApp As Object, olMail As Object
Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(0)
With olMail
.To = toAddr
.Subject = subject
.Body = bodyText
If attachPath <> "" Then .Attachments.Add attachPath
.Send
End With
LogWrite "Mail sent to " & toAddr
Exit Sub
ErrHandler:
LogWrite "Error sending mail: " & Err.Description
End Sub
VBModule5_ADO
Function GetDataFromDB(connStr As String, sql As String) As Variant
On Error GoTo ErrHandler
Dim cn As Object, rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open connStr
rs.Open sql, cn
If Not rs.EOF Then
GetDataFromDB = rs.GetRows()
End If
rs.Close
cn.Close
Exit Function
ErrHandler:
LogWrite "DB Error: " & Err.Description
End Function
VB4. 使用方法例
- CSV 読み込み → データシートに出力
Sub TestCsvRead()
Dim arr As Variant
arr = ReadCsvToArray(ThisWorkbook.Sheets("設定").Range("A1").Value)
WriteArrayToSheet arr, ThisWorkbook.Sheets("データ")
LogWrite "CSV read complete"
End Sub
VB- 安全に任意処理実行
Sub TestProcess()
SafeRun "TestCsvRead"
End Sub
VB- メール送信
Sub TestMail()
SendMail "abc@example.com", "テスト", "本文です", ""
End Sub
VB💡 このテンプレ集を使うと:
- 共通処理を使い回せる
- エラー時もログに残る
- CSV / DB / Outlook / 配列 / シート処理を統合的に扱える
- 実務で「堅牢かつ再利用可能な VBA 設計」がすぐにできる

