HOME > 即効テクニック > Excel VBA > 書式設定関連のテクニック > セルを書式で検索する(Findメソッドと引数SearchFormat)

セルを書式で検索する(Findメソッドと引数SearchFormat)|Excel VBA

書式設定関連のテクニック

セルを書式で検索する(Findメソッドと引数SearchFormat)

(Excel 2002/2003/2007/2010)

Findメソッドの引数SearchFormatをTrueにするとセルの書式を検索できます。ただし、FindNextメソッドでは書式の検索ができないので、条件を満たすすべてのセルを検索するときは、2回目以降の検索もFindメソッドを使用します。
引数SearchFormatはExcel 2002以降で使用可能です。

次のサンプルは、「実験結果」表の中で背景色が赤のセルを検索し、最小値・最大値・合計を求めます。

●サンプル●

Sub Sample()
    Dim c As Range
    Dim Rng As Range
    Dim firstAddress As String
    
    Application.FindFormat.Clear
    Application.FindFormat.Interior.Color = vbRed
    
    Set c = Range("実験結果").Find(What:="*", SearchFormat:=True)
     
    If c Is Nothing Then
        MsgBox "該当データはありません"
        Exit Sub
    Else
        firstAddress = c.Address
        Set Rng = c
        Do
            Set c = Range("実験結果").Find(What:="*", _
                                           After:=c, _
                                           SearchFormat:=True)
            If c Is Nothing Then Exit Do
            If c.Address = firstAddress Then Exit Do
            Set Rng = Union(Rng, c)
        Loop
    End If
    
    With WorksheetFunction
        MsgBox "最小値:" & .Min(Rng) & vbCrLf & _
               "最大値:" & .Max(Rng) & vbCrLf & _
               "合計 :" & .Sum(Rng)
    End With
End Sub