Search code examples
excelduplicates

How to insert 'n' number of rows based on 'n' being a number in a cell


I have a list of companies in column a. In column b, I have a number. I need to create a list where the company appears as many times in the list as the value of the number:

Company A    4
Company B    2
Company C    3  

I want:

Company A
Company A
Company A
Company A
Company B
Company B
Company C
Company C
Company C  

So, it's sort of a 'Create (n) Duplicates' function.


Solution

  • Give this a try:

    Sub KopyKat()
       Dim N As Long, i As Long, K As Long
       Dim v As String, kk As Long, m As Long
       N = Cells(Rows.Count, "B").End(xlUp).Row
       K = 1
    
       For i = 1 To N
          kk = Cells(i, "B").Value
          v = Cells(i, "A").Value
          For m = 1 To kk
             Cells(K, "C") = v
             K = K + 1
          Next m
       Next i
    End Sub
    

    enter image description here

    EDIT#1:

    Macros are very easy to install and use:

    1. ALT-F11 brings up the VBE window
    2. ALT-I ALT-M opens a fresh module
    3. paste the stuff in and close the VBE window

    If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

    To remove the macro:

    1. bring up the VBE window as above
    2. clear the code out
    3. close the VBE window

    To use the macro from Excel:

    1. ALT-F8
    2. Select the macro
    3. Touch RUN

    To learn more about macros in general, see:

    http://www.mvps.org/dmcritchie/excel/getstarted.htm

    and

    http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

    Macros must be enabled for this to work!