简体   繁体   中英

How do you split a string in a cell after every nth word into rows

How do you split a sentence after every nth word

Hi everyone, I have a long string in cell B2 that I want to split into rows based on a variable number of words that is entered in cell D2.

My string in "B2" = "One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen … … "

My variable in "D2" is 4

My result for the first line/row is "One two three four"

So far I have used this formula in "F3":

=LEFT($B$2,FIND("*",SUBSTITUTE($B$2," ","*",$D$2))-1)

for the first line/row

I need to carry on splitting the string so that the final result would be:

One two three four

five six seven eight

nine ten eleven twelve

thirteen fourteen fifteen

sixteen seventeen eighteen

nineteen … …

each of the above resulting lines in its respective row.

I don't mind the type of solution formula UDF or sub. Your help is greatly appreciated.

在第n个单词变量之后分割一个字符串

在此处输入图片说明

After using Davis' UDF

Here's a UDF that would accomplish this for you.

Public Function SplitOnNth(ByVal inputStr$, ByVal StartPos&, ByVal NumWords&) As String

    Dim arr() As String, i As Long, newArr() As String
    arr = Split(inputStr)
    ReDim newArr(NumWords - 1)

    'Arrays are zero-based, but your string isn't. Subtract 1
    For i = StartPos - 1 To StartPos + NumWords - 2
        If i > UBound(arr) Then Exit For    'Exit if you loop past the last word in string
        newArr(i - StartPos + 1) = arr(i)
    Next

    SplitOnNth = Join(newArr, " ")

End Function

This places every word that is separated by a space into an array of words. It will loop through the array to reach you max size ( NumWords argument), and output the string.

This UDF requires 3 arguments:

  • inputStr (String) : The entire string that is being used for your split
  • StartPos (Long) : The number of the first word you want to start with. In your case, 1 would start with the word One
  • NumWords (Long) : THe total words, including the one from StartPos , to include in your function's output.

The formula you would use for your first line that you show in your example would look like:

=SplitOnNth($B$2, 1, 4)

- OR -

=SplitOnNth($B$2, $E3 * $D$2 - $D$2 + 1, $D$2)

Which would result in the following output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM