簡體   English   中英

Excel VBA 通過工作表循環,當數據有多個值時插入一個新行,保持其余信息相同

[英]Excel VBA loop through worksheek, insert a new row when there are multiple values for data, keeping the rest of the information the same

我目前有大量信息,其大小各不相同。 最后一段數據可能跨越 1 列、0 列或多列。

我需要為每個單獨的數據各占一行,並且所有數據都在同一列中。

此圖顯示了原始數據和預期結果的示例

我不知道如何解決這個問題。

R=11
For each cell in Range(Range("C2"), 
Range("C2").End(xlDown))
i=0
Do
    Cells(R,1).value=cell.offset(0, -2).value
    Cells(R,2).value=cell.offset(0, -1).value
    Cells(R,2).value=cell.offset(0, i).value
    R=R+1
     i=i+1
Loop until cell.offset(0,i).value=""
Next
R=11 'the first row to paste the data 
For each cell in _
     Range(Range("C2"),Range("C2").End(xlDown))
      'cells C2 to last cell down
i=0 
Do 
    Cells(R,1).value=cell.offset(0, -2).value 'Test Data 
    Cells(R,2).value=cell.offset(0, -1).value 'Time Data 
    Cells(R,2).value=cell.offset(0, i).value 'Data
    R=R+1    'add 1 row down if have more data
    i=i+1      'i refer Data value to the right 
 Loop until cell.offset(0,i).value="" 
 Next 

如果您還想擺脫舊數據,只在此處查看新格式化的數據,我對 Lee Li Fong 的代碼進行了調整

`Sub Formating ()

'Counts how many rows of data you want to formate
With ActiveSheet
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

R = lastRow + 1 'the first row to paste the data
For Each cell In _
     Range(Range("E3"), Range("E3").End(xlDown))
      'cells E3 to last cell down
i = 0
Do
    Cells(R,1).value=cell.offset(0, -2).value 'Test Data 
    Cells(R,2).value=cell.offset(0, -1).value 'Time Data
    Cells(R, 5).Value = cell.Offset(0, i).Value 'Data
    R = R + 1 'add 1 row down if have more data
    i = i + 1  'i refer Data value to the right
 Loop Until cell.Offset(0, i).Value = ""
 Next


Worksheets("Data").Range("3:" & lastRow).EntireRow.Delete 'deletes the old unformated data

End Sub   `

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM