ここまでの要素を クラスモジュール にまとめると、
「大量データ処理を配列で高速化」+「Dictionary/Collectionで効率的に検索・集計」+「高速化設定で最適化」
を オブジェクト指向的に再利用可能な形 にできます。
クラスモジュール設計例(clsDataManager)
' === clsDataManager クラスモジュール ===
Option Explicit
Private pData As Variant
Private pRange As Range
' 初期化(範囲を配列に読み込み)
Public Sub Init(rng As Range)
Set pRange = rng
pData = rng.Value
End Sub
' 高速化開始
Public Sub BeginFast()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
End Sub
' 高速化終了
Public Sub EndFast()
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
' ユニーク値抽出(Dictionary)
Public Function GetUnique(colIndex As Long) As Variant
Dim dict As Object, i As Long
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(pData, 1)
If Not dict.Exists(pData(i, colIndex)) Then
dict.Add pData(i, colIndex), 1
End If
Next i
GetUnique = dict.Keys
End Function
' 出現回数集計(Dictionary)
Public Function GetCounts(colIndex As Long) As Object
Dim dict As Object, i As Long
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(pData, 1)
If dict.Exists(pData(i, colIndex)) Then
dict(pData(i, colIndex)) = dict(pData(i, colIndex)) + 1
Else
dict.Add pData(i, colIndex), 1
End If
Next i
Set GetCounts = dict
End Function
' ユニーク値保持(Collection)
Public Function GetUniqueCollection(colIndex As Long) As Collection
Dim col As New Collection, i As Long
On Error Resume Next
For i = 1 To UBound(pData, 1)
col.Add pData(i, colIndex), CStr(pData(i, colIndex))
Next i
On Error GoTo 0
Set GetUniqueCollection = col
End Function
' 結果を範囲に書き戻し
Public Sub WriteBack(rng As Range, arr As Variant)
rng.Resize(UBound(arr), 1).Value = Application.Transpose(arr)
End Sub
VB標準モジュールでの利用例
Sub Demo_DataManager()
Dim mgr As clsDataManager
Set mgr = New clsDataManager
' 高速化開始
mgr.BeginFast
' 初期化(A列データを対象)
mgr.Init Range("A1:A1000")
' ユニーク値抽出
Dim uniques As Variant
uniques = mgr.GetUnique(1)
mgr.WriteBack Range("C1"), uniques
' 出現回数集計
Dim dict As Object
Set dict = mgr.GetCounts(1)
Range("D1").Resize(dict.Count, 1).Value = Application.Transpose(dict.Keys)
Range("E1").Resize(dict.Count, 1).Value = Application.Transpose(dict.Items)
' 高速化終了
mgr.EndFast
End Sub
VB応用テンプレ集
- ユニーク値抽出 → Dictionary.Keys を返すメソッド
- 出現回数集計 → Dictionary.Items を返すメソッド
- 順序保持ユニーク → Collection を返すメソッド
- 大量データ処理 → 配列に読み込み、一括書き戻し
- 高速化設定 → BeginFast / EndFast メソッドで制御
- 複数表処理 → clsDataManager を複数インスタンス化して再利用
- イベント駆動型と組み合わせ → Worksheet_Change で自動集計
実務での使い分けポイント
- Dictionary → 高速検索・重複排除・集計
- Collection → 順序保持ユニーク管理
- 配列 → 大量データ処理の必須
- クラス化 → 再利用性・保守性UP
- 高速化設定 → 数万行でも一瞬で処理
💡 この「配列処理 × 高速化設定 × Dictionary / Collection × クラスモジュール」テンプレを押さえておけば、オブジェクト指向的に高速化処理を整理・再利用でき、実務の効率化に直結します。


