2

假设我有一个由空格/连字符分隔的字符串。

例如。带上这些折断的翅膀,学会飞翔。

什么vba函数可以找到破字的位置,应该返回3,而不是字符位置11。

4

2 回答 2

1

一种解决方案(可能有一种更有效的方法)是拆分字符串并遍历返回的数组:

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
于 2013-08-02T08:54:15.663 回答
1

assylias 提出的解决方案非常好,只需要稍作修改即可解决多次出现的问题:

Function wordPosition(sentence As String, searchWord As String) As Long()

    Dim words As Variant
    Dim i As Long

    words = Split(sentence, " ")
    Dim matchesCount As Long: matchesCount = 0
    ReDim matchesArray(UBound(words) + 1) As Long
    For i = LBound(words, 1) To UBound(words, 1)
        If words(i) = searchWord Then
           matchesCount = matchesCount + 1
           matchesArray(matchesCount) = IIf(i > UBound(words, 1), -1, i + 1)
        End If
    Next i

    If (matchesCount > 0) Then
       matchesArray(0) = matchesCount
    End If

    wordPosition = matchesArray

End Function


Sub AnExample()

    Dim s As String
    Dim sought As String

    s = "Take these broken wings and learn to fly and broken again"
    sought = "broken"

    Dim matches() As Long: matches = wordPosition(s, sought)

    If (matches(0) > 0) Then
       Dim count As Integer: count = 0
       Do
          count = count + 1
          MsgBox "Match No. " & count & " for " & sought & " is in position " & matches(count)
       Loop While (count < matches(0))

    End If

End Sub
于 2013-08-02T10:28:11.547 回答