Home » excel » vba – Creating an excel macro to map elements in cells to another cell

vba – Creating an excel macro to map elements in cells to another cell

Posted by: admin April 23, 2020 Leave a comment

Questions:

Okay so I have a bunch of data in table format like this:

  |A   | B             |
------------------------
1 |102 | a, b, d, f, g |
------------------------
2 |104 | a, c, e       |
------------------------

I’m new to using macros or using VBA, so is it possible to create a macro to map, individually, what’s in column B to column A like this:

  |A   | B    |
---------------
1 |102 | a    |
---------------
2 |102 | b    |
---------------
3 |102 | d    |
---------------
etc..

I’ve looked online at a bunch of VBA tutorials and don’t see anything like this.

How to&Answers:

Try below code :

Sub sample()


    Dim lastRow As Long, i As Long, j As Long
    lastRow = Range("A" & Rows.Count).End(xlUp).Row

    For i = 1 To lastRow

        temp = Split(Cells(i, 2), ",")
        For j = LBound(temp) To UBound(temp)

             Cells(Cells(Rows.Count, 3).End(xlUp).Row + 1, 3).Value = Cells(i, 1)
             Cells(Cells(Rows.Count, 4).End(xlUp).Row + 1, 4).Value = temp(j)

        Next

    Next


End Sub

enter image description here