Make the function return a boolean
:
Function contains(substring As String, testString As String) As boolean
Not sure why you are looping as you are, you can just use:
contains = InStr(1, testString, substring, vbTextCompare) > 0
Frage
Alright, I have written a UDF, which searches a given cell for a specific sub-string. It then returns TRUE is the sub-string is found in the cell, and FALSE if it is not found.
Here is the code for the UDF (named the contains
function)
Function contains(substring As String, testString As String) As String
'testString = cell to be tested for substring
Dim result As Boolean
result = False
testString = UCase(testString)
substring = UCase(substring)
For i = 1 To Len(testString)
If Mid(testString, i, Len(substring)) = substring Then result = True
Next
contains = result
End Function
The reason I created this function is so that I can nest it within stock Excel functions, mainly IF
functions, AND
functionS, and OR
functions.
However, when I use it with an OR function, the OR function does not seem to "recognize" the result of the =contains function.
Here is a screenshot of the issue within Excel:
EDIT Here is what the =contains function is doing in the above pic =contains("Hello",A2)
Obviously, since the =Contains function in column C is returning True
, then the OR
function in column D should be returning True
as well. But for some reason it is as if the stock Excel OR
function doesn't recognize the result of my contains
function.
Lösung
Make the function return a boolean
:
Function contains(substring As String, testString As String) As boolean
Not sure why you are looping as you are, you can just use:
contains = InStr(1, testString, substring, vbTextCompare) > 0