简体   繁体   English

在Excel中复制值N次

[英]Copy value N times in Excel

I have simple list: 我有简单的清单:

  A     B
item1   3
item2   2
item3   4
item4   1

Need to output: 需要输出:

  A
item1
item1
item1
item2
item2
item3
item3
item3
item3
item4

Here is one way of doing it without VBA: 这是没有VBA的一种方法:

  1. Insert a column to the left of A, so your current A and B columns are now B and C. 在A的左侧插入一列,因此您当前的A和B列现在是B和C.
  2. Put 1 in A1 在A1中放1
  3. Put =A1+C1 in A2 and copy down to A5 在A2中放置=A1+C1并向下复制到A5
  4. Put an empty string in B5, by just entering a single quote ( ' ) in the cell 在B5中输入一个空字符串,只需在单元格中输入单引号( ' )即可
  5. Put a 1 in E1, a 2 in E2, and copy down as to get 1, 2, ..., 10 在E1中加1 ,在E2中加2 ,然后复制为1,2,...,10
  6. Put =VLOOKUP(E1,$A$1:$B$5,2) in F1 and copy down. 在F1中输入=VLOOKUP(E1,$A$1:$B$5,2)并复制下来。

It should look like this: 它应该如下所示:

| A  | B     | C | D | E  | F     |
|----|-------|---|---|----|-------|
| 1  | item1 | 3 |   | 1  | item1 |
| 4  | item2 | 2 |   | 2  | item1 |
| 6  | item3 | 4 |   | 3  | item1 |
| 10 | item4 | 1 |   | 4  | item2 |
| 11 |       |   |   | 5  | item2 |
|    |       |   |   | 6  | item3 |
|    |       |   |   | 7  | item3 |
|    |       |   |   | 8  | item3 |
|    |       |   |   | 9  | item3 |
|    |       |   |   | 10 | item4 |

Here's the VBA solution. 这是VBA解决方案。 I don't quite understand the comment that VBA won't be dynamic. 我不太明白VBA不会动态的评论。 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 . 请注意,此宏将擦除Sheet1上的所有数据并将其替换为新输出 If you want the desired output on a different sheet, then change the reference to Sheet2 or what have you. 如果您希望在不同的工作表上获得所需的输出,请将参考更改为Sheet2或您拥有的内容。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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