+ Reply to Thread
Results 1 to 4 of 4

VBA to Add carriage return in cell after x number of character

Hybrid View

  1. #1
    Registered User
    Join Date
    12-06-2019
    Location
    Belfast, N. Ireland
    MS-Off Ver
    365
    Posts
    2

    VBA to Add carriage return in cell after x number of character

    I looking for vb at will format cells in a column, at 27 characters it should insert a carriage return, however this return should not be in the middle of a word, if the break were to fall in the middle of a word it would go to the previous space.


    So for example :

    This is just a sample line of text to show how I would like it formatted

    would change to the following :

    This is just a sample line
    of text to show how I would
    like it formatted

    Appreciate any help, I can get it to insert a return after x characters but only on the first occurance and cant work out to allow for not breaking words.

    Steve.
    Last edited by mbfg; 12-06-2019 at 06:58 AM.

  2. #2
    Forum Guru
    Join Date
    04-23-2012
    Location
    New Jersey, USA
    MS-Off Ver
    Excel 365
    Posts
    2,465

    Re: VBA to Add carriage return in cell after x number of character

    Give this macro a try (assumes your data is in Column A). Note the section I highlight in red as it controls where the output goes to.
    Sub WrapTextOnSpacesWithMaxCharactersPerLine()
      Dim Text As String, TextMax As String, SplitText As String
      Dim Space As Long, MaxChars As Long
      Dim Source As Range, CellWithText As Range
      
      ' With offset as 1, split data will be adjacent to original data
      ' With offset = 0, split data will replace original data
      Const DestinationOffset As Long = 1
    
      MaxChars = 27
      On Error GoTo NoCellsSelected
      Set Source = Range("A1", Cells(Rows.Count, "A").End(xlUp))
      On Error GoTo 0
      For Each CellWithText In Source
        Text = CellWithText.Value
        SplitText = ""
        Do While Len(Text) > MaxChars
          TextMax = Left(Text, MaxChars + 1)
          If Right(TextMax, 1) = " " Then
            SplitText = SplitText & RTrim(TextMax) & vbLf
            Text = Mid(Text, MaxChars + 2)
          Else
            Space = InStrRev(TextMax, " ")
            If Space = 0 Then
              SplitText = SplitText & Left(Text, MaxChars) & vbLf
              Text = Mid(Text, MaxChars + 1)
            Else
              SplitText = SplitText & Left(TextMax, Space - 1) & vbLf
              Text = Mid(Text, Space + 1)
            End If
          End If
        Loop
        CellWithText.Offset(, DestinationOffset).Value = SplitText & Text
      Next
      Exit Sub
    NoCellsSelected:
    End Sub

  3. #3
    Forum Guru
    Join Date
    08-15-2004
    Location
    Tokyo, Japan
    MS-Off Ver
    2013 O.365
    Posts
    22,834

    Re: VBA to Add carriage return in cell after x number of character

    Try
    Assuming the string is col.A.
    Sub test()
        Dim r As Range, txt As String
        With CreateObject("VBScript.RegExp")
            .Global = True
            For Each r In Range("a1", Range("a" & Rows.Count).End(xlUp))
                r = Application.Trim(Replace(r, vbLf, " "))
                .Pattern = "(.{1,27})( |$)"
                r = Application.Trim(Replace(r, vbLf, " "))
                r.Value = .Replace(r.Value, "$1" & vbLf)
                .Pattern = "\n+(?!.)"
                r.Value = .Replace(r.Value, "")
            Next
        End With
    End Sub
    If you are on Mac OS then
    Sub testNonRegX()
        Dim r As Range, txt As String, n As Long, x(), temp As Long
        For Each r In Range("a1", Range("a" & Rows.Count).End(xlUp))
            txt = Application.Trim(Replace(r, vbLf, " "))
            n = 0
            Do While Len(txt) > 27
                n = n + 1
                ReDim Preserve x(1 To n)
                temp = InStrRev(txt, " ", 28)
                x(n) = Trim$(Left$(txt, temp))
                txt = Trim$(Mid$(txt, temp + 1))
            Loop
            If Len(txt) Then
                n = n + 1: ReDim Preserve x(1 To n)
                x(n) = txt
            End If
            r.Value = Join(x, vbLf)
        Next
    End Sub
    Last edited by jindon; 12-06-2019 at 06:53 AM.

  4. #4
    Registered User
    Join Date
    12-06-2019
    Location
    Belfast, N. Ireland
    MS-Off Ver
    365
    Posts
    2

    Re: VBA to Add carriage return in cell after x number of character

    Excellent, thank you to both of you , both codes working perfectly!

+ Reply to Thread

Thread Information

Users Browsing this Thread

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

Similar Threads

  1. Expressing Carriage Return Character in a Formula
    By DobieMomPA in forum Excel General
    Replies: 4
    Last Post: 06-25-2010, 02:46 PM
  2. Carriage Return in cell
    By g48dd in forum Excel General
    Replies: 3
    Last Post: 12-28-2007, 02:24 AM
  3. Carriage return character
    By alrastro in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 08-14-2006, 01:40 PM
  4. Find max number of character and return cell address
    By ExcelMonkey in forum Excel Formulas & Functions
    Replies: 5
    Last Post: 04-14-2006, 11:13 PM
  5. What are the character codes of a carriage return entered in a comment?
    By John Wirt in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 08-03-2005, 04:01 PM
  6. Replies: 2
    Last Post: 07-26-2005, 02:05 PM
  7. Replies: 6
    Last Post: 03-23-2005, 11:06 PM
  8. [SOLVED] How do I add a carriage return into a cell in Excel?
    By pm in forum Excel General
    Replies: 3
    Last Post: 02-14-2005, 09:06 PM

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