The code I posted yesterday was put together hurriedly and didn't handle some possible errors
such as (1) a source cell that is empty (you can't resize a range to 0 columns!) or (2) a source
cell that is so close to the right edge of the worksheet that there aren't enough columns
available to handle the text (you can't resize a range so that it extends past column IV,
either!).
It also wasn't optimized for speed, i.e. turning of screen updating, event processing, and
setting calculation to manual, minimizing the creation of new strings. The version below takes
care of those issues. It creates only one new string for each segment of the text (rather than
3).
Option Explicit
Option Base 0
Sub SplitText2()
Dim Cell As Range
Dim Length As Long
Dim MaxCols As Long
Dim p As Long
Dim s As Long
Dim sp As Long
Dim sText As String
Dim TheSegments() As String
Dim Settings As Variant
Const MaxLength As Long = 20
Const SpaceChar As String = " "
With Selection
MaxCols = .Parent.Columns.Count - .Column
End With
ReDim TheSegments(0 To MaxCols - 1)
With Application
Settings = Array(.Calculation, .ScreenUpdating, .EnableEvents)
End With
For Each Cell In Selection.Columns(1).Cells
sText = Application.Trim(Cell.Text)
Length = Len(sText)
If Length > 0 Then
s = 0
p = 1
Do While p <= Length
If s = MaxCols - 1 Then
'no more space to the right, so
'put entire tail into last column
TheSegments(s) = Mid$(sText, p)
p = Length + 1
ElseIf (Length - p + 1) > MaxLength Then
'more than MaxLength chars left, try to split it
sp = InStrRev(sText, SpaceChar, p + MaxLength)
If sp >= p Then
'space found, split text there
TheSegments(s) = Mid$(sText, p, sp - p)
p = sp + 1
Else
'no space found -- take MaxLength characters
'(i.e. will split in middle of a word)
TheSegments(s) = Mid$(sText, p, MaxLength)
p = p + MaxLength
End If
Else
'remaining text <= MaxLength characters,
'no need to split it
TheSegments(s) = Mid$(sText, p)
p = Length + 1
End If
s = s + 1
Loop
Cell.Offset(0, 1).Resize(1, s).Value = TheSegments()
End If
Next Cell
With Application
s = LBound(Settings)
.Calculation = Settings(s)
.ScreenUpdating = Settings(s + 1)
.EnableEvents = Settings(s + 2)
End With
End Sub