Home » excel » How to split a column in Excel into multiple columns, using categories from another column?

How to split a column in Excel into multiple columns, using categories from another column?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a very large data set with hundreds of thousands of rows. I have managed to split it into two columns like so:

Name:           | John
Birth year:     | 1982
Favorite sport: | Rugby
Favorite color: | Blue
                |
Name:           | Mike
Birth year:     | 1977
                |
Name:           | Shayla
Favorite sport: | Soccer
                |
Name:           | Kimberly
Birth year:     | 1983
Favorite sport: | Baseball
Favorite color: | Yellow
Favorite food:  | Pizza

However, I want to eliminate the repetition of categories that currently exists. How do I split each data “entry” into separate rows or columns and use the “categories” so that none repeat, like so:

Name    | Birth year    |  Favorite sport  |  Favorite color  |  Favorite food
John    | 1982          |  Rugby           |  Blue            |
Mike    | 1977          |                  |                  |
Shayla  |               |  Soccer          |                  |
Kimberly| 1983          |  Baseball        |  Yellow          | Pizza

It should be noted that the existing data set will contain the name plus one or more categories

How to&Answers:

Try something like this:

Set fields = CreateObject("Scripting.Dictionary")
fields.Add "Name:"           , 1
fields.Add "Birth year:"     , 2
fields.Add "Favorite sport:" , 3
fields.Add "Favorite color:" , 4
fields.Add "Favorite food:"  , 5

Set xl = CreateObject("Excel.Application")
xl.Visible = True

Set wb = xl.Workbooks.Open("C:\path\to\your.xls")
Set src = wb.Sheets(1)
Set dst = wb.Sheets(2)

i = 0
For Each row In src.UsedRange.Rows
  key = row.Range("A1").Value
  val = row.Range("B1").Value

  If key = "Name:" Then i = i+1
  If key <> "" Then
    If fields.Exists(key) Then
      dst.Cells(i+1, fields(key)).Value = val
    Else
      WScript.Echo "Unknown key " & key
    End If
  End If
Next

wb.Save
wb.Close

xl.Quit