How to get multiple copies of a cell in a single r

2019-07-27 11:44发布

I would like to use vba code that can sort this problem out.

I have a row and i want multiple copies of each cell in the same row. It needs to copy the cell by n-numbers. In row 1 will be the information to be copied. and in row 2 the n-number.

So the example:

Input: (say the n-number = 3)

  • John
  • Hendrik
  • Sara

Output:

  • John
  • John
  • John
  • Hendrik
  • Hendrik
  • Hendrik
  • Hendrik
  • Sara
  • Sara
  • Sara ....

Hope someone could help me out!

1条回答
三岁会撩人
2楼-- · 2019-07-27 12:33

From:

enter image description here

To:

enter image description here

Use this code:

Option Explicit

Sub CopyInAWeirdWay()
    Dim sh As Excel.Worksheet
    Dim LastRow As Long
    Dim currentCopyRow As Long
    Dim i As Long
    Dim k As Long

    Set sh = ActiveSheet
    LastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row
    currentCopyRow = 1

    For i = 1 To LastRow
        For k = 1 To sh.Cells(i, 2)
            sh.Cells(currentCopyRow, 3).Value = sh.Cells(i, 1).Value
            currentCopyRow = currentCopyRow + 1
        Next k
    Next i
End Sub
查看更多
登录 后发表回答