[On Edit:我修改了该函数,以便如果最后一个参数是整数,则它扮演compareMode
参数输入Instr
(0 表示区分大小写,这是默认值,1 表示不区分大小写)。作为最后的调整,您还可以为可选的最终参数传递布尔值而不是整数True
对应于不区分大小写和False
对应默认区分大小写]
如果你经常做这种事情,那么编写一个类似于以下的函数是有意义的inStr
但可以处理多种模式。ParamArray
是一个自然使用的工具:
Function Contains(str As String, ParamArray args()) As Boolean
Dim i As Long, n As Long, mode As Integer
n = UBound(args)
If TypeName(args(n)) <> "String" Then
mode = args(n)
mode = Abs(mode) 'So True => -1 => 1 for case-insensitive search
n = n - 1
End If
For i = 0 To n
If InStr(1, str, args(i), mode) > 0 Then
Contains = True
Exit Function
End If
Next i
Contains = False
End Function
测试如下:
Sub Test()
Debug.Print Contains("General Electric", "Gas", "Electric", "Oil")
Debug.Print Contains("General electric", "Gas", "Electric", "Oil")
Debug.Print Contains("General electric", "Gas", "Electric", "Oil", False)
Debug.Print Contains("General electric", "Gas", "Electric", "Oil", True)
Debug.Print Contains("General electric", "Gas", "Electric", "Oil", 1)
Debug.Print Contains("General Motors", "Gas", "Electric", "Oil")
End Sub
Output:
True
False
False
True
True
False