スペース/ハイフンで区切られた文字列があるとします。
例えば。この破れた翼を取り去ってもう一度空を飛ぶことを覚えよう。
文字位置である 11 ではなく、3 として返される壊れた単語の位置を見つけることができる vba 関数は何ですか。
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
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