我是VBA编程的初学者,我遇到了子字符串搜索的问题,在字符串中找到一个或多个关键字。
我在这个论坛的答案上得到了帮助,但是代码将搜索限制在字符串中的第一个单词而不是整个字符串。在答案中指出“记住,开头与包含不同。”
我试图通过将使用“StringStarts”的代码部分更改为“Contains”来修改代码,但这并没有改变。
初步答案见于: Multiple string search with InStr function in VBA
代码如下:
"If StringStarts(Me.gname.Value, "Mr", "Mrs", "Dr", "Supreme Commander", "Capt.") Then
MsgBox "Consumer Name Starts with Mr./Mrs./Ms./Dr. Check Consumer Name"
...
Function StringStarts(strCheck As String, ParamArray anyOf()) As Boolean
Dim item As Long
For item = 0 To UBound(anyOf)
If InStr(1, strCheck, anyOf(item), vbTextCompare) = 1 Then
StringStarts = True
Exit Function
End If
Next
End Function"
这是我发布的第一个问题,所以我希望我一直遵循这些约定。
答案 0 :(得分:1)
anyOf
函数返回通过Function StringContains2(strCheck As String, ParamArray anyOf()) As Long
Dim item As Long
For item = 0 To UBound(anyOf)
If InStr(1, strCheck, anyOf(item), vbTextCompare) = 0 Then Exit For
Next
StringContains2 = item
End Function
数组传递的字符串的数量包含在作为参数传递的第一个字符串中:
Sub main()
Dim msg As String, strng As String
strng = Me.gname.Value
Select Case StringContains2(strng, "Mr", "Mrs", "Dr", "Supreme Commander", "Capt.")
Case 0
msg = "there was no keyword in the string"
Case Is > 1
msg = "there were two or more keywords in the string"
End Select
If msg <> "" Then MsgBox msg, vbCritical
End Sub
用作:
form +++ Section("contacts-selected")
答案 1 :(得分:0)
我知道这个问题/答案很旧,但是我发现它正在寻找“ VBA字符串包含许多字符串之一”,所以其他人也可能如此。
接受的答案告诉了我关于ParamArray
的信息,我从未使用过它,但是代码也没有按照它说的去做,因为StringContains2
返回了第一场比赛的位置找到了,如果没有找到第一个单词(例如“先生”),那么甚至都不会检查其他单词。
例如,如果我设置strng = "Dr Mrs Mrs Capt. Supreme Commander Dave"
,然后main
在我猜您希望它返回5
时说“没有关键字”。
使用InStr
时还存在一个问题,如果您要查找“ Mr”,并且名字是“ Imram Dave先生”,由于它使用vbTextCompare
会在两个地方找到“ Mr”忽略大小写。尽管在这段代码中,它只会返回1
,因为它只检查anyOf
中的每个项目一次,并且InStr返回找到的第一个位置,而不是出现次数。
如果您想输入零个或多个错误消息,则意味着要确保该名称包含标题标题的一个且只有一个,并且可能与“ Mr ”或“先生”。 (但在考虑大小写且不会错误地标记任何内容时),因此正确处理起来确实很复杂。
但是您可以使用Ubound
和Split
的组合来获取一个字符串在另一个字符串中出现的次数,所以这是我的修改:
Function StringContains(stringToCheck As String, stringsToCheckFor As Variant) As Long
Dim item As Long
Dim occurrencesFound As Integer
For item = 0 To UBound(stringsToCheckFor)
occurrencesFound = occurrencesFound + UBound(Split(stringToCheck, stringsToCheckFor(item), , vbBinaryCompare))
Next
StringContains = occurrencesFound
End Function
Sub Test_StringContains()
Dim msg As String, test As String
Dim titles As Variant
titles = Array("Mr ", "Mr.", "Mrs ", "Mrs.", "Dr ", "Dr.", "Supreme Commander", "Capt ", "Capt.")
test = "Mr Mrs. Mrs Dr Supreme Commander Dave"
Debug.Print "Input: " & test & " has " & StringContains(test, titles) & " occurrences."
'Input: Mr Mrs. Mrs Dr Supreme Commander Dave has 5 occurrences.
test = "Mr Commander Dave"
Debug.Print "Input: " & test & " has " & StringContains(test, titles) & " occurrences."
'Input: Mr Commander Dave has 1 occurrences.
test = "MrDave"
Debug.Print "Input: " & test & " has " & StringContains(test, titles) & " occurrences."
'Input: MrDave has 0 occurrences.
End Sub