The header should be written to each new column inserted, and the cell value should split by the "," delimiter.
Example:
Before:
Header name | another columns from right... |
---|---|
value1 | |
value1,value2,value3 | |
value1,value2 |
After:
Header name | Header name | Header name | another columns from right... |
---|---|---|---|
value1 | |||
value1 | value2 | value3 | |
value1 | value2 |
So far I tried:
Function multipleValues(colName As String)
Set Rng = getHeadersRange(colName)
colNumber = Rng.Columns(Rng.Columns.Count).Column
ColLtr = Cells(1, colNumber).Address(True, False)
ColLtr = Replace(ColLtr, "$1", "")
Dim indexOfWord As Integer
Dim maxValues As Integer
'Find out how many new columns needs to be inserted
Dim item As String, newItem As String
Dim items As Variant, newItems As Variant
maxValues = 0
For Each cell In Rng
items = Split(cell.Value, ",")
If maxValues < UBound(items) Then
maxValues = UBound(items)
End If
Next cell
'Insert new columns
If maxValues > 0 Then
Columns(Rng.Column).Offset(, 1).Resize(, maxValues).Insert
End If
'Duplicate the header to the new columns
'For i = 1 To maxValues
'Cells(1, ColLtr + i).Value = colName
'Next i
'Split the items to columns
For Each cell In Rng
items = Split(cell.Value, ",")
maxValues = UBound(items)
For i = 0 To UBound(items)
firstValue = items(0)
cell.Offset(0, i) = items(i)
cell.Value = firstValue
Next i
Next cell
End Function
Currently, I get the new columns with their values except for the header row values.
I would do the following:
First find out how many columns need to be added. We do that by counting the delimiters (commas) in the column and use the maximum + 1 to get the amount of columns we will have in the end after splitting.
Then we read the data of the column into a
Data
array for faster processing and prepare anOutput
array in the calculated size.Then we multiply the header to the
Output
array and split the data rows into the output array.Finally we just need to add the right amount of columns to the right and fill in the data from our array.
done.
To turn this
into this
/// Edit
And well of course as Siddharth Rout pointed out correcty you can still use the text to column feature if you add in the blank columns that are needed to expand the data. In the end this method would be more efficient.