Copy value N times in Excel

前端 未结 2 1310
春和景丽
春和景丽 2020-12-14 13:06

I have simple list:

  A     B
item1   3
item2   2
item3   4
item4   1

Need to output:

  A
item1
item1
item1
item2
item2
ite         


        
2条回答
  •  执笔经年
    2020-12-14 13:47

    Here's the VBA solution. I don't quite understand the comment that VBA won't be dynamic. It's as dynamic as you make it, just like a formula. Note that this macro will erase all data on Sheet1 and replace it with the new output. If you want the desired output on a different sheet, then change the reference to Sheet2 or what have you.

    Option Explicit
    
    Sub MultiCopy()
    
    Dim arr As Variant
    Dim r As Range
    Dim i As Long
    Dim currRow As Long
    Dim nCopy As Long
    Dim item As String
    
    'store cell values in array
    arr = Sheet1.UsedRange
    currRow = 2
    
    'remove all values
    Sheet1.Cells.ClearContents
    Sheet1.Range("A1") = "A"
    
    For i = 2 To UBound(arr, 1)
        item = arr(i, 1)
        nCopy = arr(i, 2) - 1
        If nCopy > -1 Then
            Sheet1.Range("A" & currRow & ":A" & (currRow + nCopy)).Value = item
            currRow = currRow + nCopy + 1
        End If
    Next
    
    End Sub
    

提交回复
热议问题