Here is the finished product. Its a simple VBA routine that will work
with any data and is not dependent on the size of the text strings. The
only hardcoded values I used, and I will replace with a prompt, is the
starting cells for both the search strings and the cells on which to
perform the search. I used the solution Biff developed for my work
requirement because I wanted to use native Excel rather than maintain
custom code. Our office performs a lot of data collection for monthly
performace stats and often the volumes of data we get are in the
thousands of rows and routines like this can be a big time saver.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Search for occurance in a Cell of a string found in a specific Cell
' Two letters found in Columns 3 - 10 will be used as the String to
Search for
' in the next cell in the 2nd column. When a match is found, increment
the match counter
' When the end of the the cell is encountered, advance to the next cell.
' Loop will continue until search cell is blank.
' At the end of each search cell put match counter in approprirate row
and column
' Need nested loops to traverse both the Search Cell and the String Cells.
' Define variables
Dim CellString As String 'Cell to search
Dim SearchString As String ' String search for
Dim I As Integer
Dim CharCnt As Integer ' Character Position in Search Cell
Dim CellRow As Integer ' Row for Search Cell, also used for inner loop
control and row to write resluts
Dim CellCol As Integer ' Column for Search Cell
Dim SearchCol As Integer ' Cell Coloumn for String to Search for, also
for outer loop control and column to write results
Dim SearchRow As Integer ' Cell Row for string to search for
Dim MatchCnt As Integer ' Number of times the Search string is found
in the search cell.
Dim Returncode As Integer
'Initialize variables
CharCnt = 1 'first character of cell to look for match
CellRow = 2 ' Initialize Cell Row
CellCol = 2 'Initialize Cell Column B
SearchRow = 1 'Initialize Search String Row
SearchCol = 3 'Initialize Search String Column C
MatchCnt = 0 ' Initialize Match counter
Returncode = 1 ' varible to capture the position where match was found
' Outer loop controls the column used to get the search string
' Inner loop controls which cell to search for matches
Do While Len(Cells(CellRow, CellCol).Value) > 0
SearchString = Cells(SearchRow, SearchCol) ' Get the string to
search for
CellString = Cells(CellRow, CellCol) 'get the search string
Do While Len(SearchString) > 0
Returncode = 1
Do Until Returncode = 0
Returncode = InStr(CharCnt, CellString, SearchString, vbTextCompare)
If Returncode > 0 Then
MatchCnt = MatchCnt + 1
CharCnt = Returncode + 1
Else
Cells(CellRow, SearchCol).Value = MatchCnt
End If
Loop
' Need to get next Search String and reset CellString pointer and
clear matchcnt.
CharCnt = 1
MatchCnt = 0
SearchCol = SearchCol + 1
SearchString = Cells(SearchRow, SearchCol)
Returncode = 0
Loop
CellRow = CellRow + 1
SearchCol = 3
Loop
End Sub