|
'Call this function to search a string for another one
Public Function Search(searchfor As String, searchin As String, startat
As Variant, matchcase As Variant)
'Error Trapping:
'If length of the search item is less that the string to search in then
end
If Len(searchfor) > Len(searchin) Then Search = -1: GoTo done 'Set
Search to -1 to show error
'If length of search item of string to search in is less than 1 then end
If Len(searchfor) < 1 Or Len(searchin) < 1 Then Search = -1: GoTo
done 'Set Search to -1 to show error
'If case is to be matched then set the search item and
string to search in all to lower case
If matchcase = 1 Then searchin = LCase$(searchin): searchfor = LCase$(searchfor)
'Begin searching at startat
For x = startat To Len(searchin)
'Find length to search for
length = Len(searchfor)
'Look in string to find string same length as search item
searched = Mid$(searchin, x, length)
'If searched equals the search item then set Search as where it was found
and end
If searched = searchfor Then Search = x: GoTo done
Next x
'Search item not found - set Search to show this
Search = 0
'Finished
done:
End Function
'Example of use:
Private Sub Command1_Click()
'Set values
start = 1
foundonce = 0
st:
'Call the function - 1st parameter as search item, 2nd as to search in
string, 3rd as where to start searching in the string and 4th as whether
to match the case or not
Value = Search(Text1.Text, Text2.Text, start, 1)
'If value is 0 and foundonce is 0 then it the search
item has not been found - indicate this
If Value = 0 And foundonce = 0 Then MsgBox "Not Found!": GoTo
done
'If value is 0 but foundonce does not equal 0 then the
search item has been found once and the searchin string has been finished
searching in - so end
If Value = 0 Then GoTo done
'If value = -1 then there was an error - indicate this
If Value = -1 Then MsgBox "Error!": GoTo done
'If the search item was found, say where:
MsgBox "Found beginning at character: " & Value
'Change start to the new value
start = Value + 1
'Set foundonce to show that at least 1 instance was found - so it does
not say 'Not Found!' when finishing
foundonce = 1
'Redo searching at the new point to find other instances
GoTo st
'Finished
done:
|