在Excel中使用vba结合基于产品id列的行

我正在尝试使用VBA将基于产品ID列的行组合到一行示例中:

╔═════════════╦════════════════════╦═══════════════╦════════════╦═════════════════════╦═══════════════╦══════════╦══════════════╦══════════════════════════╦═══════════════╗ ║ ProjectCode ║ ProjectDescription ║ CUSTOMER Name ║ PRODUCT ID ║ PRODUCT DESCRIPTION ║ SUPPLIER Name ║ CUSTOMER ║ INVOICED QTY ║ Price Incl Vat SUPPLIER ║ PURCHASED QTY ║ ╠═════════════╬════════════════════╬═══════════════╬════════════╬═════════════════════╬═══════════════╬══════════╬══════════════╬══════════════════════════╬═══════════════╣ ║ 1 ║ one ║ ║ 123 ║ ONE TWO THREE ║ SUPPLIER ║ ║ ║ $51.12 ║ 200 ║ ╠═════════════╬════════════════════╬═══════════════╬════════════╬═════════════════════╬═══════════════╬══════════╬══════════════╬══════════════════════════╬═══════════════╣ ║ 1 ║ one ║ CUSTOMER ║ 123 ║ ONE TWO THREE ║ ║ ║ 170 ║ $51.12 ║ ║ ╠═════════════╬════════════════════╬═══════════════╬════════════╬═════════════════════╬═══════════════╬══════════╬══════════════╬══════════════════════════╬═══════════════╣ ║ 1 ║ one ║ CUSTOMER ║ 123 ║ ONE TWO THREE ║ ║ ║ 30 ║ $51.12 ║ ║ ╚═════════════╩════════════════════╩═══════════════╩════════════╩═════════════════════╩═══════════════╩══════════╩══════════════╩══════════════════════════╩═══════════════╝ 

期望的结果:

 ╔═════════════╦════════════════════╦═══════════════╦════════════╦═════════════════════╦═══════════════╦══════════╦══════════════╦══════════════════════════╦═══════════════╗ ║ ProjectCode ║ ProjectDescription ║ CUSTOMER Name ║ PRODUCT ID ║ PRODUCT DESCRIPTION ║ SUPPLIER Name ║ CUSTOMER ║ INVOICED QTY ║ Price Incl Vat SUPPLIER ║ PURCHASED QTY ║ ╠═════════════╬════════════════════╬═══════════════╬════════════╬═════════════════════╬═══════════════╬══════════╬══════════════╬══════════════════════════╬═══════════════╣ ║ 1 ║ one ║ CUSTOMER ║ 123 ║ ONE TWO THREE ║ SUPPLIER ║ ║ 200 ║ $51.12 ║ 200 ║ ╚═════════════╩════════════════════╩═══════════════╩════════════╩═════════════════════╩═══════════════╩══════════╩══════════════╩══════════════════════════╩═══════════════╝ 

这应该做你想要的。 它将“Sheet1”到“Sheet2”的行结合起来,并假定您的发票客户数量在列“H”中。 请注意,对于一组具有相同ID的行,第一行将被复制,并且只更新列“H”:

 Option Explicit Sub CombineLines() Dim wSht1 As Worksheet, wSht2 As Worksheet Set wSht1 = Sheets("Sheet1") Set wSht2 = Sheets("Sheet2") Dim r As Integer: r = 2 Dim rLast As Integer, rs As Integer, r2 As Integer: r2 = 2 Dim tot As Double With wSht1 .Rows(1).Copy wSht2.Rows(1).PasteSpecial Paste:=xlPasteAll rLast = .Cells(.Rows.Count, "A").End(xlUp).Row Do While r <= rLast If .Cells(r, "A") = .Cells(r + 1, "A") Then rs = r tot = 0# Do While .Cells(r, "A") = .Cells(r + 1, "A") tot = tot + .Cells(r, "H").Value r = r + 1 Loop tot = tot + .Cells(r, "H").Value Else tot = .Cells(r, "H").Value rs = r End If .Rows(rs).Copy wSht2.Rows(r2).PasteSpecial wSht2.Cells(r2, "H").Value = tot r2 = r2 + 1 r = r + 1 Loop End With End Sub