我希望你们中的一个人能帮我解决这个问题。我需要创建某种宏或 VBA 代码来拆分和操作 Excel 中的数据行。
对于此示例,我们有 5 行数据。前 3 行是订单号 0000000000-00 的商品信息,后 2 行是订单号 0000000000-01 的商品信息。我需要为每个订单号设置一行(“HDR”),为每个订单的每个产品设置一行(“ITM”)。我在下面提供了一个示例,展示了我将收到的数据和期望的结果。
原始数据:
order-id product-num date buyer-name product-name quantity-purchased
0000000000-00 10000000000000 5/29/2014 John Doe Product 0 1
0000000000-00 10000000000001 5/29/2014 John Doe Product 1 2
0000000000-00 10000000000002 5/29/2014 John Doe Product 2 1
0000000000-01 10000000000002 5/30/2014 Jane Doe Product 2 1
0000000000-01 10000000000003 5/30/2014 Jane Doe Product 3 1
期望的结果:
HDR 0000000000-00 John Doe 5/29/2014
ITM 10000000000000 Product 0 1
ITM 10000000000001 Product 1 2
ITM 10000000000002 Product 2 1
HDR 0000000000-01 Jane Doe 5/30/2014
ITM 10000000000002 Product 2 1
ITM 10000000000003 Product 3 1
任何帮助都将不胜感激!谢谢。
答案1
这个宏可以执行您想要的操作,但它仅使用您提供的数据进行测试(尽管如果它以相同的方式继续,应该没问题,问题将出在您添加更多列时,但代码应该很容易更新)
Sub SortMeOut()
Dim previousOrderId As String
Dim row As Integer
row = 2
previousOrderId = Worksheets("Sheet1").Range("A2").Value
Dim offset As Integer
offset = 0
Do While (True)
If Worksheets("Sheet1").Range("A" & row).Value = "" Then
Exit Do
End If
Dim isHeader As Boolean
isHeader = True
Do While (True) 'loop through all columns with a match
If Worksheets("Sheet1").Range("A" & row).Value <> previousOrderId Then
Exit Do
End If
If Not isHeader Then
Worksheets("Sheet2").Range("A" & row + 1 + offset).Value = "ITM"
Worksheets("Sheet2").Range("B" & row + 1 + offset).Value = Worksheets("Sheet1").Range("B" & row).Value ' product num
Worksheets("Sheet2").Range("C" & row + 1 + offset).Value = Worksheets("Sheet1").Range("E" & row).Value ' product name
Worksheets("Sheet2").Range("D" & row + 1 + offset).Value = Worksheets("Sheet1").Range("F" & row).Value ' quantity
End If
If isHeader Then
Worksheets("Sheet2").Range("A" & row + offset).Value = "HDR"
Worksheets("Sheet2").Range("B" & row + offset).Value = Worksheets("Sheet1").Range("A" & row).Value 'order id
Worksheets("Sheet2").Range("C" & row + offset).Value = Worksheets("Sheet1").Range("D" & row).Value ' name of the dude
Worksheets("Sheet2").Range("D" & row + offset).Value = Worksheets("Sheet1").Range("C" & row).Value ' date
'we also have to do the first item as well...
Worksheets("Sheet2").Range("A" & row + 1 + offset).Value = "ITM"
Worksheets("Sheet2").Range("B" & row + 1 + offset).Value = Worksheets("Sheet1").Range("B" & row).Value ' product num
Worksheets("Sheet2").Range("C" & row + 1 + offset).Value = Worksheets("Sheet1").Range("E" & row).Value ' product name
Worksheets("Sheet2").Range("D" & row + 1 + offset).Value = Worksheets("Sheet1").Range("F" & row).Value ' quantity
isHeader = False
End If
row = row + 1
Loop
offset = offset + 1
previousOrderId = Worksheets("Sheet1").Range("A" & row).Value
Loop
End Sub
它假设数据在工作表 1 上,并将结果溢出到工作表 2 上
前
后