I have a string of seven words and I have a 1d array (5 elements). How to split the string so as to put each word in an element of the array .. so the first word goes to the first element .. and so on. The fourth word goes to the fourth element. The rest of the words (the fifth - the sixth - the seventh) go to the last and fifth element of the array. Of course, the string may vary in the number of words.
In another case, if the string consists of only three words, then the first word to the first element, the second word to the second element but the last word should go to the last (fifth) element of the array.
I am trying the following, but the last element has incorrect result. It should have `of seven words`
Code: Select all
Sub Test_SplitWords_UDF()
Dim v
v = SplitWords("This Is A String Of Seven Words")
End Sub
Function SplitWords(ByVal sInputString As String)
Dim Words() As String, SplitWord() As String, sTemp As String, i As Long
Words = Split(sInputString, " ")
If UBound(Words) <= 4 Then
ReDim SplitWord(0 To 4)
For i = 0 To UBound(Words) - 1
SplitWord(i) = Words(i)
Next i
SplitWord(UBound(SplitWord)) = Words(UBound(Words))
Else
ReDim SplitWord(0 To 4)
For i = 0 To 3
SplitWord(i) = Words(i)
Next i
If UBound(Words) > 3 Then
For i = 4 To UBound(Words)
sTemp = sTemp & IIf(sTemp = Empty, Empty, " ") & Words(i)
Next i
SplitWord(4) = sTemp
End If
'SplitWord(4) = Join(Split(Join(Words, " "), " ", 4), " ")
End If
SplitWords = SplitWord
End Function
Code: Select all
For i = 4 To UBound(Words)
SplitWord(4) = SplitWord(4) & IIf(SplitWord(4) = Empty, Empty, " ") & Words(i)
Next i