|
|
This function counts the number of occurrences of a substring within a string. Optionally will look for the "whole word" instead of any occurrance. CODE ' Code courtesy of UtterAccess Wiki ' http://www.utteraccess.com/wiki/index.php?title=GetStrOccurrences ' ' You are free to use this code in any application, ' provided this notice is left unchanged. ' ' REV DATE DESCRIPTION ' 1.0 2012-02-06 initial release ' 2.0 2012-03-15 added whole word option Public Function GetStrOccurrences(ByVal strSearchFor As String _ , ByVal strSearchString As String _ , Optional intCompare = vbTextCompare _ , Optional blWholeWord As Boolean = False) As Long 'Searchs through the strSearchString for strSearchFor and returns the number 'of times that strSearchFor occurs. Dim aStrip() As Byte If Len(strSearchFor) = 0 Then Exit Function If blWholeWord = True Then 'Strip the confusing characters aStrip = "~!@#$%^&*()_+=-{}`""'?/><.,[]|\" & vbCr & vbLf & vbTab 'Modify per your scenario. Dim i As Long For i = LBound(aStrip) To UBound(aStrip) Step 2 strSearchString = Replace(strSearchString, Chr(aStrip(i)), " ", 1, , vbTextCompare) Next i 'Pad the string being searched AS WELL AS the string being sought. Plus, dbl-space 'the delimiter (string being sought) so the Split() works correctly. strSearchString = " " & Replace(strSearchString, " " & strSearchFor & " ", _ " " & strSearchFor & " ", , , intCompare) strSearchFor = " " & strSearchFor & " " End If GetStrOccurrences = UBound(Split(strSearchString, _ strSearchFor, , _ intCompare)) End Function
|
| This page was last modified 14:54, 16 March 2012. This page has been accessed 107 times. Disclaimers |