简体   繁体   中英

How to insert/copy in Excel base on number of another column in Excel VBA or not

Basically, I would like a simple way to the following example scenario : Number of times of A,B and C copied based on lines of numbers. Number of lines are much more than below example in real cases of course.

From

A  1
B  2
C  3
   6
   7

to

A  1
A  2
A  3
A  6
A  7
B  1
B  2
B  3
B  6
B  7
C  1
C  2
C  3
C  6
C  7

Any quick way?

To follow up,

Below function and VBA solved my question above.

Used below function to get the first column

=INDEX(Sheet1!A:A,ROUNDUP(ROW()/5,0))

Anyone know a corresponding VBA code for this part? The function works, however, it is not very convenient when there are too many lines. It will be great to set range in VBA.

The second column used VBA code as below (Tried multiple columns so be VBA is slightly different with the question) :

Sub Macro1()
    '
    ' Macro1 Macro
    '
    Dim lastRow As Long

    ' Subdivision total row number
    a = Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row
    ' Porject total row number
    b = Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).Row
    Sheets("Sheet1").Select
    ' Project total cell range
    Range("B1:C5").Copy
    Range("F1").Select
    Sheets("Sheet1").Paste
    ' Row number need to -1 as the first copy is done above
    For i = 1 To A - 1
        lastRow = Sheets("Sheet1").Cells(Rows.Count, "F").End(xlUp).Row + 1
        Range("F" & lastRow).Select
        ActiveSheet.Paste
    Next
End Sub

Below function and VBA solved my question above.

Used below function to get the first column

=INDEX(Sheet1!A:A,ROUNDUP(ROW()/5,0))

Anyone know a corresponding VBA code for this part? The function works, however, it is not very convenient when there are too many lines. IT will be great to set range in VBA.

The second column used VBA code as below (Tried multiple columns so be VBA is slightly different with the question) :

Sub Macro1()
'
' Macro1 Macro
'
 Dim lastRow As Long

 ' Subdivision total row number
    a = Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row
  ' Porject total row number
    b = Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).Row
        Sheets("Sheet1").Select
    ' Project total cell range
    Range("B1:C5").Copy
    Range("F1").Select
    Sheets("Sheet1").Paste
    ' Row number need to -1 as the first copy is done above
  For i = 1 To A - 1
    lastRow = Sheets("Sheet1").Cells(Rows.Count, "F").End(xlUp).Row + 1
    Range("F" & lastRow).Select
    ActiveSheet.Paste
  Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM