将Excel垂直数据更改为水平[NOT TRANSPOSE]

时间:2014-10-03 20:42:37

标签: excel

我经常需要获取与标识符绑定的项目列表(如订单号)并将其转换为一条记录。

a   | b
101 | medium t-shirt
101 | medium socks

a   | b              | c
101 | medium t-shirt | medium socks

有关如何轻松完成此任务的任何想法?请记住,我想这样做到500行的清单。

2 个答案:

答案 0 :(得分:0)

根据提供的示例提供的内容应该可行(我说应该因为我手边没有Excel,所以代码未经测试):

Sub JoinByID()

    Dim dct As Dictionary
    Dim i As Long, j As Long
    Dim iIDCol As Integer
    Dim rFirst As Range
    Dim sID As String
    Dim col As Collection
    Dim ws As Worksheet, wsNew As Worksheet
    Dim vLoopIDs As Variant, vLoopVals As Variant

    Set rFirst = Sheets(1).Range("A1") 'change to where your data starts
    Set ws = rFirst.Parent
    iIDCol = rFirst.Column
    ' loop through data and collect based on ID
    For i = rFirst.Row + 1 To rFirst.End(xlDown).Row
        sID = ws.Cells(i, iIDCol).Value
        If dct.Exists(sID) Then
           dct(sID).Add ws.Cells(i, iIDCol + 1).Value
        Else
           Set col = New Collection
           col.Add ws.Cells(i, iIDCol + 1).Value
           dct.Add sID, col
        End If
    Next i

    ' drop the data in a new sheet
    Set wsNew = Worksheets.Add
    i = 0
    With wsNew
         For Each vLoopIDs In dct.Keys
             i = i + 1
             .Cells(i, 1) = vLoop
             j = 1
             For Each vLoopVals In dct(vLoop)
                 j = j + 1
                 .Cells(i, j) = vLoopVals
             Next vLoopVals
         Next vLoopIDs
    End With

End Sub

注意:您需要添加对Microsoft Scripting Runtime的引用才能使Dictionary可用。

答案 1 :(得分:0)

输入C2:

=IF(D2=FALSE,B3,B2)  
D2中的

=ISODD(ROW())

并将两者都复制到适合的地方。

在顶部选择全部,复制,选择性粘贴,值。过滤以在ColumnD中选择TRUE并删除标题下方的所有可见内容。取消过滤,删除过滤器并删除ColumnD。