8

I am trying to check if a sting has a space in it. The following is not working for me.

if (skpwords.contains(lcase(query)) And Mid(query, InStrRev(query, " "))) then

end if

3 Answers3

17

The proper way to check if a string contains a character (or substring) is to use the InStr() function. It will return the one-based index of the position within the string where the text was found. So, a return value > 0 indicates a successful find. For example:

If InStr(query, " ") > 0 Then
    ' query contains a space
End If

The InStr() function can optionally take three or four arguments as well. If you want to specify a starting index, use the three-argument version:

If InStr(3, query, " ") > 0 Then
    ' query contains a space at or after the 3rd character
End If

If you want to perform a case-insensitive search (the default is case-sensitive), then use the four-argument version. Note that there is no three-argument version of this function that allows you to specify case sensitivity. If you want to perform a case-insensitive search, you must always supply the starting index, even if you want to start your search at the beginning (1):

If InStr(1, query, "A", vbTextCompare) > 0 Then
    ' query contains "a" or "A"
End If
Bond
  • 16,071
  • 6
  • 30
  • 53
1

You could split the array using Ubound and check the length of the array to determine if there are spaces

VBS Example:

hi = "What is up"
spaces = Ubound(Split(hi, " "))
if (spaces = 0) then
    Wscript.Echo "No Spaces"
else
    Wscript.Echo "There are spaces"
end if
Dom Slee
  • 611
  • 1
  • 5
  • 10
0

The best and shortest possible answer to this would be where you use the Instr function. This can be in the below format as ::

mysentence = "This is a sentence" 
if Instr(mysentence, " ")>0 Then
 'do your stuff here..
else
 ' do else stuff here.. 
End if
Ram Mehta
  • 449
  • 1
  • 6
  • 20