如何根据某些列的数据将行拆分为多行

时间:2019-11-26 00:51:36

标签: excel vba

我有一个包含预订数据的电子表格。我想根据标题为“预订时间”字符串的列包含数据来将一行拆分为多行。

这是一个例子

 ID |  SlotNo. | Delivery Date  | Booking No. | Book Time 1 | Truck Sz 1 | Book Time 2 | Truck Sz 2
 1      10415      12/31/2019      10001          00:00         B'Double     00:20         Single

输出

ID |  SlotNo. | Delivery Date  | Booking No. | Book Time | Truck Size |
1      10415     12/31/2019       10001         00:00      B'Double
1      10415     12/31/2019       10001         00:20      Single

我在这里Similar solution尝试过使用解决方案,但是看来问题并不那么相似。

我想根据“预订时间”列中的数据如何拆分行。实际上最多有30个“预订时间”列。

1 个答案:

答案 0 :(得分:0)

Dim shtIn As Worksheet, shtOut As Worksheet
Dim c As Range, c2 As Range

Set shtIn = ThisWorkbook.Sheets("Input")
Set shtOut = ThisWorkbook.Sheets("Output")

Set c = shtIn.Range("A2") 'start of your data
'do while "ID" not empty
Do While Len(c.Value) > 0
    Set c2 = c.EntireRow.Cells(1, "E") 'first "book time" for this row
    'do while "book time" not empty
    Do While Len(c2.Value) > 0
        With shtOut.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
            c.Resize(1, 4).Copy .Cells(1)
            c2.Resize(1, 2).Copy .Cells(1).Offset(0, 4)
        End With
        Set c2 = c2.Offset(0, 2) 'next book time
    Loop
    Set c = c.Offset(1, 0)
Loop