假设我有一个由空格/连字符分隔的字符串。
例如。带上这些折断的翅膀,学习飞翔。
什么vba函数可以找到单词损坏的位置,应该返回3,而不是字符位置11。
最佳答案
一种解决方案(可能有一种更有效的方法)是分割字符串并迭代返回的数组:
Function wordPosition(sentence As String, searchWord As String) As Long
Dim words As Variant
Dim i As Long
words = Split(sentence, " ")
For i = LBound(words, 1) To UBound(words, 1)
If words(i) = searchWord Then Exit For
Next i
'return -1 if not found
wordPosition = IIf(i > UBound(words, 1), -1, i + 1)
End Function
你可以这样调用它:
Sub AnExample()
Dim s As String
Dim sought As String
s = "Take these broken wings and learn to fly"
sought = "broken"
MsgBox sought & " is in position " & wordPosition(s, sought)
End Sub
关于string - 如何查找字符串中的单词位置(而不是字符位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18012485/