エクセルマクロ クラスの使い方覚書

自分用覚書記事です

エクセルでの検索系マクロを書く上での
カスタムを意識した設計のものをひとつ

標準モジュール

'ループしながら検索した単語の含まれる
'座標と内容を返す。
Public Function search(ByVal searchStr As String) As Variant

Dim c As Range
Dim first As String
' 最初の検索
Set c = Cells.Find(searchStr)
If c Is Nothing Then
    Exit Function
End If

'1回めの検索ヒット処理
first = c.address
Debug.Print (c.address)

'型宣言と代入
Dim ret As cellData
Set ret = New cellData

ret.address = c.address


Dim retList(2) As Variant
Set retList(1) = ret

'以下2回目以降ループ処理
Do
    ' c に対する処理

    ' 次を検索
    Set c = Cells.FindNext(c)
    If c Is Nothing Then
        Exit Do
    End If
    If c.address = first Then
        Exit Do
    End If
    
    'インスタンス生成による初期化(上書き)
    Set ret = New cellData
    
    'アドレスの代入
    ret.address = c.address
    Set retList(2) = ret
    
Loop

'戻り値に結果を代入
search = retList

End Function


Sub main()
    Dim mainList() As Variant
    
    Debug.Print ("--search開始--")
    mainList = search("特許")
    Debug.Print ("--searchおわり--")
    
    Debug.Print ("-----------------")
    Debug.Print (mainList(1).address)
    Debug.Print (mainList(2).address)
    Debug.Print ("-----------------")

End Sub

クラスモジュール(cellData)

'検索セルのデータ
'検索でヒットしたアドレス
Public address As String
'検索でヒットした文の内容
Public contents As String