半角チルダ

ExcelVBA、その他。
覚え書きや、補足資料などのスクラップブック。
end-u(1037781)

■FindNext メソッドの使用例

2009-02-16 22:50:00 | 気をつけたほうがいいこと
既にメジャーな話なのですが、VBAヘルプの『FindNext メソッドの使用例』によろしくない例示があります。
以下はExcel2000でのヘルプ抜粋です。
FindNext メソッドの使用例

次の使用例はセル範囲 A1:A500 で、値に 2 が含まれていて灰色表示のセルを検索します。

With Worksheets(1).Range("a1:a500")
  Set c = .Find(2, LookIn:=xlValues)
  If Not c Is Nothing Then
    firstAddress = c.Address
    Do
      c.Interior.Pattern = xlPatternGray50
      Set c = .FindNext(c)
    Loop While Not c Is Nothing And c.Address <> firstAddress
  End If
End With


1)FindNextのLoop終了条件に『Not c Is Nothing』は不要。(※)

検索でヒットしたセルをRange変数 c にセットして FindNextメソッドを実行しているのだから、通常では c がNothingになる事はなく、終了条件として考慮する必要はない(はず)です。
Findメソッドで1つのセルのみがヒットした場合でも、次にFindNextメソッドを実行した時にその元のセルがヒットするわけなので、c はNothingになる事はありません。
(検索条件である『値が 2』のセルの値を書き換える処理をLoop内で処理している場合は別です)

2)仮に『c Is Nothing』が成立した場合、『c.Address <> firstAddress』は判定できない。

というか、『c Is Nothing』の場合、Nothingな c に Addressプロパティはありえないのでエラーになります。
Excel2002のヘルプから FindNext メソッドの使用例が変更されましたが、まさにこの事例通りエラーになります。
http://msdn.microsoft.com/ja-jp/library/cc329003.aspx



また、あまり知られていない事みたいですが、前述(1)(※)には例外があります。
(実はここからが本題だったりして)
Findメソッドを実行してセットしたRange変数が、FindNext メソッドを実行した時にNothingになるケースです。
Sub test()
  Dim c As Range
  Dim firstAddress As String

  With Sheets.Add
    With .Range("A10")
      .Value = "a"
      .Resize(2).Merge
    End With
    Set c = .Cells.Find(What:="a", _
              After:=.Cells(1), _
              LookIn:=xlFormulas, _
              LookAt:=xlPart, _
              SearchOrder:=xlByRows, _
              SearchDirection:=xlNext, _
              MatchCase:=False)
    If Not c Is Nothing Then
      firstAddress = c.Address
      Do
        c.Interior.Color = vbYellow
        Set c = .Cells.FindNext(c)
        Stop
        If c Is Nothing Then Exit Do
      Loop While c.Address <> firstAddress
      Set c = Nothing
    End If
  End With
End Sub

つまり、検索条件にヒットするセルが1個のみの場合で、かつ、そのセルが縦方向の結合セルの場合、
『c Is Nothing』が発生します。

念のための対策として
>If c Is Nothing Then Exit Do
などとしておいたほうが良いかもしれません。

Comment    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« ■AutoFilter FilterModeでのF... | TOP | ■WorkSheet.Copy時のイベント »
最新の画像もっと見る

Recent Entries | 気をつけたほうがいいこと