Sub WrapTextOnSpacesWithMaxCharactersPerLine()
Dim Text As String, LF As Long, 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 = Application.InputBox("Maximum number of characters per line?", Type:=1)
If MaxChars <= 0 Then Exit Sub
On Error GoTo NoCellsSelected
Set Source = Application.InputBox("Select cells to process:", Type:=8)
On Error GoTo 0
For Each CellWithText In Source
Text = CellWithText.Value
SplitText = ""
Do While Len(Text) > MaxChars
TextMax = Left(Text, MaxChars + 1)
LF = InStr(TextMax, vbLf)
If LF Then
SplitText = SplitText & Left(TextMax, LF)
Text = Mid(Text, LF + 1)
Else
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
End If
Loop
CellWithText.Offset(, DestinationOffset).Value = SplitText & Text
Next
Exit Sub
NoCellsSelected:
End Sub |