Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

Macro that uses FindNext to search for specific format finds wrong cell in Excel


View products that this article applies to.

This article was previously published under Q282151

↑ Back to the top


Symptoms

When you use a Microsoft Visual Basic for Applications macro to search for cells with specific formatting, the macro may incorrectly find cells that do not match the formatting that you specified.

↑ Back to the top


Cause

This behavior can occur because the macro uses the FindNext or FindPrevious method, each of which ignores format settings used in the preceding Find method.

NOTE: If you click Find Next while recording a macro, the FindNext method is used.

↑ Back to the top


Workaround

To work around this behavior, replace all instances of FindNext and FindPrevious with Find. The second and subsequent Find commands need to have the optional After and SearchFormat parameters.

For example, if the recorded code appears as follows
Application.FindFormat.Interior.ColorIndex = 6
Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=True).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
				
replace the second two instances of Cells.FindNext(After:=ActiveCell).Activate with the Find method as follows:
Application.FindFormat.Interior.ColorIndex = 6
Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=True).Activate
Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=True).Activate
Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=True).Activate
				

↑ Back to the top


Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the "Applies to" section.

↑ Back to the top


Keywords: KB282151, kbpending, kbbug

↑ Back to the top

Article Info
Article ID : 282151
Revision : 5
Created on : 1/29/2007
Published on : 1/29/2007
Exists online : False
Views : 316