Sunday, December 5, 2010

Using Find Method in Code

Sometimes in Excel Macro coding, when you are required to find any specific cell value and execute the list of codes. It becomes extremely time taking when you loop through all cells in the excel column.The simple solution is to use the Find method in Excel Code.

Set rFound_Cell=Columns(2).Find(What:="$$", after:=Cells(1,1), LookIn:=xlValues, _
    LookAt:=xlPart, SearchOrder:=xlByRows, _
    searchdirection:=xlNext, MatchCase:=False)

SRow=rFound_Cell.Row

What if there are multiple matching cells and you got to loop through each time the match occurs -
Use the Countif Function to establish the number of occurrence of string or value in the sheet and then loop it.

Dim rFound_Cell As Range
Set rFound_Cell = Range("B1")
Sheets("Sheet1").Select
For i = 1 To WorksheetFunction.CountIf(Columns(2), "($$$)")

      Set rFound_Cell = Columns(2).Find(What:="($$$)", after:=rFound_Cell, LookIn:=xlValues, _
                                    LookAt:=xlPart, SearchOrder:=xlByRows, _
                                    searchdirection:=xlNext, MatchCase:=False)
      SRow = rFound_Cell.Row

Next i

No comments:

Post a Comment