Question

So I have data in format :

data1|data2|data3|data4|data5|data6|... etc.

I want Word to put enter (break line) after every 5th occurence of | in order to structure and separate data.

I cant find a simple and quick way to doing that. Any ideas?

Was it helpful?

Solution

Use the built-in Split function and rebuild the data string using the vbCrLf constant to add the line-feed.

Note that the Split function removes the delimiter, so if you need it in the output, you have to add it back when you add the strings in the For loop.

Something like the following could work:

Option Explicit

Sub GroupDataStringByFive()
    Dim sIn As String
    Dim sOut As String
    Dim sArr() As String
    Dim iForCounter As Integer

    sIn = "data1|data2|data3|data4|data5|data6"

    sArr = Split(sIn, "|")

    If IsArray(sArr) Then
       For iForCounter = 0 To UBound(sArr)
           If iForCounter > 0 And iForCounter Mod 5 = 0 Then
               sOut = sOut & vbCrLf & sArr(iForCounter)
           Else
               sOut = sOut & sArr(iForCounter)
           End If
       Next iForCounter
    End If

    MsgBox sOut
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top