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

时间:2017-03-30 21:06:41

标签: excel vba excel-vba

我知道有几个问题和答案关于使用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”列。

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

2 个答案:

答案 0 :(得分:2)

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

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  

答案 1 :(得分:2)

你可以使用Application.Index()

来处理数组和切片它们
Sub main()
    Dim data1 As Variant, data2 As Variant
    Dim i As Long

    With Range("A2", Cells(Rows.Count, "A").End(xlUp))
        data1 = .Resize(, 3).Value
        data2 = .Offset(, 3).Resize(, 25).Value
        .Resize(, 28).ClearContents
    End With
    For i = LBound(data1) To UBound(data1)
        With Cells(Rows.Count, 1).End(xlUp).Offset(1)
            .Resize(data1(i, 3), 3) = Application.Index(data1, i, 0)
            .Offset(, 3).Resize(data1(i, 3), 1) = Application.Transpose(Application.Index(data2, i, 0))
        End With
    Next
End Sub