Add rows based on the value of a cell.

Solved
supermajo Posted messages 20 Status Member -  
supermajo Posted messages 20 Status Member -
Hello,

I have a file with several thousand rows.

In cell D2, there is a number that indicates the number of rows - 1, that I need to duplicate.
Example:
if it says 3, Excel should duplicate the row 2 times.
If it says 5, it should duplicate the row 4 times, etc...

I don't know how to create a macro.
Can someone help me?
Thank you very much.

3 answers

  1. via55 Posted messages 14393 Registration date   Status Member Last intervention   2 759
     
    Hello supermajo

    Developer tab - Visual Basic (or ALT + F11) to open the VBA editor
    Insert - Module then copy and paste the following macro into the page and close the editor
    Sub ajout() Dim Ligne As Long Ligne = Columns(4).Find("*", , , , xlByColumns, xlPrevious).Row For n = Ligne To 1 Step -1 nl = Range("D" & n) - 1 If nl > 0 Then For x = 1 To nl Rows(n + 1 & ":" & n + 1).Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Next End If Next End Sub

    Developer tab - Macros - Select ajout then Run

    Best regards
    Via

    --
    "Imagination is more important than knowledge." A. Einstein
    0
    1. supermajo Posted messages 20 Status Member
       
      Good evening Via55,

      Thank you for your quick response.

      I just tested it.
      Blank lines were added, but I got an error message

      "runtime error '13'
      Type mismatch

      And when I clicked on Unblock, it was the line

      nl = Range("D" & n) - 1

      that was highlighted in yellow.

      I don't understand what that means. Is it because the contents of the cells in the columns were not duplicated?

      Thank you again for your valuable help.

      Best regards.
      0
    2. supermajo Posted messages 20 Status Member
       
      Hello

      Here is the link to the file.

      https://www.cjoint.com/c/HLrlHRU3BEz

      Column D is in standard format...
      Should it be changed to number format?

      Thanks again
      0
    3. via55 Posted messages 14393 Registration date   Status Member Last intervention   2 759
       
      Re

      The bug is simply due to the title line which is of course not a number
      Just modify the macro line
      For n = Line To 1 Step -1
      to
      For n = Line To 2 Step -1

      No need to change the format of the column

      Best regards
      Via
      0
    4. supermajo Posted messages 20 Status Member
       
      Thank you very much via55.
      Best regards
      0