andnand
New Member
Hi Everybody,
I have the following:
- Based on the content in column A
- Content is one or more lines, separated by char(13), every line with a different length
The following workbook does the following:
- Splits the lines in the adjacent cells
- Cell length limit is 220
- No line is broken between cells
- Every content from column A produces a different amount of splitting cells
- Only 5 cells/rows with content in attachment, number of rows can be 1000.
The problem is sometimes last cells have very few lines compared to the previous ones within the same row.
How do I redistribute the content so (on each row):
- The amount of lines per cell is similar
- The number of cells with content per row is exactly the same as with the current code
- The length limit of the cell remains 220
- No line is broken between cells
Thank you!!
I have the following:
- Based on the content in column A
- Content is one or more lines, separated by char(13), every line with a different length
The following workbook does the following:
- Splits the lines in the adjacent cells
- Cell length limit is 220
- No line is broken between cells
- Every content from column A produces a different amount of splitting cells
- Only 5 cells/rows with content in attachment, number of rows can be 1000.
The problem is sometimes last cells have very few lines compared to the previous ones within the same row.
How do I redistribute the content so (on each row):
- The amount of lines per cell is similar
- The number of cells with content per row is exactly the same as with the current code
- The length limit of the cell remains 220
- No line is broken between cells
Thank you!!
Code:
Sub SplitContent()
Dim ws As Worksheet
Dim lastRow As Long
Dim sourceRange As Range
Dim targetRange As Range
Dim cell As Range
Dim sourceText As String
Dim lines() As String
Dim resultLines() As String
Dim resultIndex As Long
Dim line As String
Dim i As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set sourceRange = ws.Range("A2:A" & lastRow)
For Each cell In sourceRange
sourceText = cell.Value
lines = Split(sourceText, Chr(13))
resultIndex = 0
ReDim resultLines(0 To 0)
For i = LBound(lines) To UBound(lines)
If Len(resultLines(resultIndex)) + Len(lines(i)) + 1 <= 220 Then
resultLines(resultIndex) = resultLines(resultIndex) & lines(i) & Chr(13)
Else
resultIndex = resultIndex + 1
ReDim Preserve resultLines(0 To resultIndex)
resultLines(resultIndex) = lines(i) & Chr(13)
End If
Next i
For i = 0 To UBound(resultLines)
ws.Cells(cell.Row, i + 2).Value = Left(resultLines(i), Len(resultLines(i)) - 1)
Next i
Next cell
End Sub