vba - Excel VBA根据单元格值插入行并根据该数字向下复制列

标签 vba excel

我知道有关使用 Excel VBA 根据单元格值复制和插入行有几个问题和答案,但我有一个额外的要求,因此很难找到解决方案。我现在陷入困境,需要帮助。

我有一个电子表格,内容如下:

Name    Unit    Count   Req1    Req2    Req3    Req4    ...  ...    Req25
Apple   304     5       Apple1  Apple2  Apple3  Apple4  ... Apple5  
Pear    562     2       Pear1   Pear2                   
Kiwi    471     4       Kiwi1   Kiwi2   Kiwi3   Kiwi4           

电子表格包含“Req1”到“Req25”的列。如果“count”是5,则“Req1”到“Req5”列将有数据。每行的“计数”会有所不同,将列的提醒保留为“Req25”空白。我需要根据“count”-1 插入行,将所有列复制到“count”列,然后将“Req2”、“Req3”等向下移动到“Req1”列中相应的插入行。我可能没有很好地解释它。

我需要最终结果如下:

Name    Unit    Count   Req1
Apple   304     5       Apple1
Apple   304     5       Apple2
Apple   304     5       Apple3
Apple   304     5       Apple4
Apple   304     5       Apple5
Pear    562     2       Pear1
Pear    562     2       Pear2
Kiwi    471     4       Kiwi1
Kiwi    471     4       Kiwi2
Kiwi    471     4       Kiwi3
Kiwi    471     4       Kiwi4

我能够插入正确的行数,但我坚持循环遍历列并将它们向下移动到“Req1”列。

非常感谢任何帮助!提前致谢!

最佳答案

这个宏将执行您想要的操作,但它不会插入行,而是将数据放入新工作表中;您只需要添加一个输出表并在代码中更改输入和输出表的名称即可。

Dim mOut As Worksheet
Dim mInp As Worksheet
Dim num As Integer
Dim i As Integer
Dim j As Integer
Dim c As Integer

Sub Copy()

Set mInp = Worksheets("Your Sheet Name")
Set mOut = Worksheets("Create Another Sheet for Output")

mOut.Cells(1, 1) = mInp.Cells(1, 1)
mOut.Cells(1, 2) = mInp.Cells(1, 2)
mOut.Cells(1, 3) = mInp.Cells(1, 3)
mOut.Cells(1, 4) = "Req"

i = 2
num = 2

While mInp.Cells(i, 1) <> ""
c = mInp.Cells(i, 3)

For j = 1 To c

mOut.Cells(num, 1) = mInp.Cells(i, 1)
mOut.Cells(num, 2) = mInp.Cells(i, 2)
mOut.Cells(num, 3) = mInp.Cells(i, 3)
mOut.Cells(num, 4) = mInp.Cells(i, j + 3)

num = num + 1
Next j

i = i + 1
Wend

End Sub

如果您想通过插入行来寻求解决方案,则需要在插入行后添加此循环。此外,您需要在添加行时计算行数。我没有您的代码来了解如何完成它,但我确信这样做很容易。

 For i = 2 To NumRows 'Number of rows (Sum of the inserted and original rows)
         If mInp.Cells(i, 1) <> "" Then

             irow = i
             Count = 1

         Else

             mInp.Cells(i, 1) = mInp.Cells(irow, 1)
             mInp.Cells(i, 2) = mInp.Cells(irow, 2)
             mInp.Cells(i, 3) = mInp.Cells(irow, 3)
             mInp.Cells(i, 4) = mInp.Cells(irow, 4 + Count)

             Count = Count + 1

         End If
 Next i  

关于vba - Excel VBA根据单元格值插入行并根据该数字向下复制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128336/

相关文章:

javascript - 如何在 CasperJS 中使用 excel 文件(xlsx)的 'row elements'?

.net - 错误 : <target>. ColumnName 和 <source>.ColumnName 具有冲突的属性:DataType 属性不匹配

ms-access - 将表单打开到特定选项卡

vba - 根据单元格的值隐藏 Excel 中的多列

vba - 使用 UTF-8 编码将工作表保存到 TXT

VBA:如何在 <td> 标签中获取隐藏的href

vba - 代码有错误 : unable to get the vlookup property of the worksheetfunction class

vba - 分析 Microsoft Word 的 VBA 代码

excel - 导入数据覆盖下拉列表数据

vba - 在 VBA 上使用当前日期重命名工作表