実務向けフル機能テンプレ Excel VBA
ここからは、実務向けフル機能 Excel VBA テンプレ の設計例を作成します。
すべての機能を組み込みつつ、モジュール分割・安全処理・ログ管理・進捗バー対応 まで入れた構成です。
機能一覧
- CSV 読み込み(配列高速処理)
- フォルダ一括処理(複数ブック・ファイルを開く)
- ADO DB 接続(SQL クエリ実行)
- ログローテーション(古いログ自動削除)
- 進捗バー(処理状況可視化)
- Outlook メール送信(アドレス・件名・本文)
- エラー統合処理&ログ
- 設定値を「設定」シートにまとめ外部化
- 業務処理モジュール(Sub/Function 分割)
モジュール構成(おすすめ)
| モジュール | 役割 |
|---|---|
| M_Main | メイン処理の呼び出し |
| M_Common | 共通関数:Nz, ToHankaku, 設定取得など |
| M_ErrorHandler | 統一エラー処理 |
| M_Log | ログ書き込み、ログローテーション |
| M_Progress | 進捗バー制御 |
| M_FileIO | CSV 読み込み・フォルダ一括処理 |
| M_DB | ADO 接続・SQL 実行 |
| M_Outlook | メール送信 |
| M_Business | 業務固有処理 |
サンプルコード抜粋(主要機能)
① ログ+ログローテーション
Option Explicit
Sub LogWrite(msg As String)
Dim sh As Worksheet
Set sh = Sheets("ログ")
' ログローテーション: 1000行超えたら先頭削除
If sh.Cells(Rows.Count, 1).End(xlUp).Row > 1000 Then
sh.Rows("2:2").Delete
End If
Dim nextRow As Long
nextRow = sh.Cells(Rows.Count, 1).End(xlUp).Row + 1
sh.Cells(nextRow, 1).Value = Now
sh.Cells(nextRow, 2).Value = msg
End Sub
VB② CSV 読み込み(高速配列)
Function ReadCSV(path As String) As Variant
Dim f As Integer, line As String
Dim arr() As Variant, tmp() As String
Dim i As Long: i = 0
If Dir(path) = "" Then Exit Function
f = FreeFile
Open path For Input As #f
Do Until EOF(f)
Line Input #f, line
tmp = Split(line, ",")
ReDim Preserve arr(0 To i, 0 To UBound(tmp))
Dim j As Long
For j = 0 To UBound(tmp)
arr(i, j) = tmp(j)
Next j
i = i + 1
Loop
Close #f
ReadCSV = arr
End Function
VB③ フォルダ一括処理
Sub ProcessFolder(folderPath As String)
Dim fName As String
fName = Dir(folderPath & "\*.xlsx")
Do While fName <> ""
Workbooks.Open folderPath & "\" & fName
LogWrite "Opened: " & fName
' 業務処理呼び出し
Workbooks(fName).Close SaveChanges:=True
fName = Dir()
Loop
End Sub
VB④ ADO DB 接続
Function GetDBData(connStr As String, sql As String) As Variant
Dim cn As Object, rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open connStr
rs.Open sql, cn
GetDBData = rs.GetRows
rs.Close
cn.Close
End Function
VB⑤ 進捗バー(UserForm + Label)
Sub ShowProgress(total As Long)
Dim frm As UserForm1
Set frm = New UserForm1
frm.Label1.Width = 0
frm.Show vbModeless
Dim i As Long
For i = 1 To total
frm.Label1.Width = i / total * frm.Frame1.Width
DoEvents
Next i
Unload frm
End Sub
VB⑥ Outlook メール送信
Sub SendMail(toAddr As String, subject As String, body As String)
Dim olApp As Object, olMail As Object
Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(0)
With olMail
.To = toAddr
.Subject = subject
.Body = body
.Send
End With
LogWrite "Mail sent to " & toAddr
End Sub
VB実務向け設計ポイント
- 全処理は M_Main から呼び出す
- Sub/Function は責務ごとに分割
- ログは必ず書き、必要に応じてローテーション
- エラーは M_ErrorHandler に統合
- CSV/DB/フォルダ/メールなどは共通モジュール化
- 進捗バーでユーザーの待ち時間可視化
- 設定値は「設定」シートにまとめ、外部化

