Hi,
I googled and copy/pasted this sub routine,
I call it to search thru a range for all occurrences of a value, but it's only finding the value once even though the value occurs several times in the range. I've tried debugging, but can't see the problem.
Really appreciate if someone could show me how to correct the code so it finds all the occurrences of the value in the range.
Thanks
I googled and copy/pasted this sub routine,
Code:
Sub findComplaint(searchItem, itemGroup, totRows)
' the passed parameters are: searchitem - the value to search for, itemGroup - the value to update the next cell with, totRows - total rows in range to search.
'finding multiple occurrences of a value in a range
Dim rngSearch As Range, rngLast As Range, rngFound As Range
Dim strFirstAddress As String
Set rngSearch = Sheets(2).Range("H2:H" & totRows) 'set the search range:
' Set rngSearch = ActiveSheet.Range("A1:A100")
Set rngLast = rngSearch.Cells(rngSearch.Cells.Count) 'specify last cell in range:
'Find the string in "searchItem" in search range, when it first occurs.
' Note that the After argument is used to begin search after the
' last cell in the search range.
Set rngFound = rngSearch.Find(what:=searchItem, After:=rngLast, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not rngFound Is Nothing Then 'if searchItem is found in search range:
strFirstAddress = rngFound.Address 'saves the address of the first occurrence of searchItem, in the strFirstAddress variable:
Do
'Find next occurrence of searchItem.
'Note, that we do not start from the first
'occurrence of "searchitem" (ie. strFirstAddress).
Set rngFound = rngSearch.FindNext(rngFound)
rngFound.Offset(, 1).Value = itemGroup 'put itemGroup in Group Title (Col I) for the complaint:
'The Loop ends on reaching the first occurrence
'of "searchItem" (ie. strFirstAddress).
'We have retained the value of "searchItem" till this step
'because if in the first occurrence, "searchItem" had been
'replaced by "NewItem", this step would give an error.
'I do not understand the above comment
Loop Until rngFound.Address = strFirstAddress
End If
End Sub
Really appreciate if someone could show me how to correct the code so it finds all the occurrences of the value in the range.
Thanks