[英]Excel VBA to insert rows based on cell value and copy columns down based on that number
我知道有幾個問題和答案關於使用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
您可以使用數組並使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.