You can often use the Instr function in an unorthodox way to write more concise code. A typical example is when you need to test a single character:
' test whether CHAR contains a vowel' the standard wayIf UCase$(char) = "A" Or UCase$(char) = "E" Or UCase$(char) = "I" Or UCase$ _ (char) = "O" Or UCase$(char) = "U" Then ' it is a vowelEnd If' the more concise solutionIf InStr("AaEeIiOoUu", char) Then ' it is a vowelEnd If
You can also use InStr to check the contents of a variable against a list of multi-character words, using a delimiter character that can’t appear in the word:
' test whether WORD contains the name of a season' the standard wayIf LCase$(word) = "winter" Or LCase$(word) = "spring" Or LCase$(word) = _ "summer" Or LCase$(word) = "fall" Then ' it is a season's nameEnd If' the more concise wayIf Instr(";winter;spring;summer;fall;", ";" & word & ";") Then ' it is a season's nameEnd If
In some sames you can even use InStr to replace a Select Case block, but you must pay a lot of attention to the number of characters in the arguments:
' convert a string in the range from "zero" to "nine" to the corresponding ' numeric value:' the standard waySelect Case LCase$(word) Case "zero" result = 0 Case "one" result = 1 Case "two" result = 2 Case "three" result = 3 Case "four" result = 4 Case "five" result = 5 Case "six" result = 6 Case "seven" result = 7 Case "eight" result = 8 Case "nine" result = 9End Select' the more concise way' note that the longest word in the list is 5 characters long, so we must' pad shorter strings with the necessary number of semicolonsresult = InStr(";zero;;one;;;two;;;three;four;;five;;six;;;seven;eight;nine;", _ ";" & LCase$(word) & ";") 6