+ Reply to Thread
Results 1 to 2 of 2

VBA to Insert Enter After Every 5th Word, Unless Comma Precedes

Hybrid View

  1. #1
    Registered User
    Join Date
    06-14-2011
    Location
    Denver, Colorado
    MS-Off Ver
    Excel 2003
    Posts
    81

    VBA to Insert Enter After Every 5th Word, Unless Comma Precedes

    Hello anyone!

    I have a paragraph of text in Microsoft word. I want to break the paragraph into lines either after every 5th word in the string, or after commas/periods, whichever comes first.

    For example:

    The dog is sitting on the floor. It is thirsty, and it pants for water. The dog's owner pours the dog a fresh bowl of water. etc.

    turns into ->

    The dog is sitting on (note: 5 words)
    the floor. (note: period comes first)
    It is thirsty, (note: comma comes first)
    and it pants for water. (note: 5 words)
    The dog's owner pours the (note: 5 words)
    dog a fresh bowl of (note: 5 words)
    water. (note: period comes first)


    Thank you!!!
    P.S. The notes in parentheses are just notes, not what should be output by the VBA code.

  2. #2
    Forum Contributor
    Join Date
    01-07-2013
    Location
    south africa
    MS-Off Ver
    Excel 2003-13
    Posts
    210

    Re: VBA to Insert Enter After Every 5th Word, Unless Comma Precedes

    Hello
    As I post for Excel, I have done the code suitable for Excel. It may be suitable for Word, but I have not tried it as such

    Sub test()
        Dim maxwords As Integer
        Dim sentence As Variant
        Dim phrase As Variant
        Dim nextpiece As Variant
        Dim wordcount As Integer
        
        stop1 = "."
        stop2 = ","
        
        sentence = ActiveCell.Value
        For n = 1 To Len(sentence)
            nextpiece = Mid(sentence, n, 1)
            phrase = phrase & nextpiece
            
            If nextpiece = " " Then
                If Len(phrase) > 1 Then wordcount = wordcount + 1  'check needed to catch space after stops
            Else
                'do nothing
            End If
            
            If (nextpiece = stop1 Or nextpiece = stop2 Or wordcount = 5) Then
                ActiveCell.Offset(1, 0).Value = phrase
                ActiveCell.Offset(1, 0).Activate
                phrase = ""
                wordcount = 0
            End If
        Next n
    End Sub
    Regards
    Most helpful to mark solved items as such (see help for directions). Star ratings are always welcome.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1