Thread: FindNext Errors
View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default FindNext Errors

It's a problem with the sample code in VBA's help. In earlier versions, the
code didn't change the .value, it just changed the formatting (font or fill or
something).

In this version, the 2s are changed to 5s. After the last 2 is changed, then
this line:

set c = .findnext(c)
will result in C being nothing -- it wasn't found.

Excel's vba checks both conditions ("Not c is nothing" and "c.address <
firstaddress") in that "while" statement.

Since c is nothing, then c.address fails.

Personally, I find it easier to just check to see if the code should drop out of
the loop myself:

Option Explicit
Sub testme()
Dim c As Range
Dim FirstAddress As String
With Worksheets(1).Range("a1:a500")
Set c = .Find(2, LookIn:=xlValues)
If Not c Is Nothing Then
FirstAddress = c.Address
Do
c.Value = 5
Set c = .FindNext(c)
If c Is Nothing Then
Exit Do
End If
If c.Address = FirstAddress Then
Exit Do
End If
Loop
End If
End With
End Sub

ps. I would also include all the parms on the .find statement. If you don't,
then you'll get the same choices as the user made in the last Edit|Find or the
choices made in last .find in code.




Geoff wrote:

I simply cannot get the Help example on FindNext to work. Even explicitly
setting the find paramaeters still results in err 91. The example cell value
is changed but then errors out at Loop While.

The problem seems to be with c.address. What am I missing?

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

Geoff


--

Dave Peterson