Right now I have a long list of "Industry" values that users have submitted through a form. I've written a macro that will search for particular terms in those values and paste values that conform to my significantly smaller list of "acceptable" Industry values. The point is to reclassify all of the current industry values users have submitted into my existing taxonomy. Here's the way my If-Then statements look as of right now:
If InStr(1, Cells(i, "A").Value, "Energy") > 0 Or InStr(1, Cells(i, "A").Value, "Electricity") > 0 Or InStr(1, Cells(i, "A").Value, "Gas") > 0 Or InStr(1, Cells(i, "A").Value, "Utilit") > 0 Then
Cells(i, "B").Value = "Energy & Utilities"
End If
It's pretty ugly. Works perfectly fine, but is a bear to read. My macro is littered with these barely-intelligible If-Then statements, and it's difficult to read through it all. Is there any way to pass multiple values to the "String2" argument of Instr
?
There is no way to pass multiple parameters to InStr, but you could create your own sub that handles it. I would create a sub that takes the string to look in and an array of strings to search for. It could then loop over the array and call InStr for each string. Have it return a final result of whether it found all of them or not, and then replace all of your ugly conditional statements with one call to your sub.
[On Edit: I modified the function so that if the last argument is an integer it plays the role of the
compareMode
parameter inInstr
(0 for case-sensitive search, which is the default, and 1 for case-insensitive). As a final tweak, you could also pass a Boolean rather than an integer for the optional final argument withTrue
corresponding to case-insensitive andFalse
corresponding to the default case-sensitive]If you do this sort of thing a lot it makes sense to write a function which is similar to
inStr
but can handle multiple patterns.ParamArray
is a natural tool to use:Tested like:
Output: