更改csv文件的格式

时间:2015-07-09 09:57:13

标签: excel csv excel-formula

我有一个csv文件,格式如下:

name1
Date,Type
11/06/2015 18:13:42,Red
name2
Date,Type
08/06/2015 18:53:38,Blue
name3
Date,Type
10/06/2015 17:13:33,Yellow
10/06/2015 17:55:11,Green
name4
Date,Type
15/06/2015 11:19:01,Blue
10/06/2015 13:45:05,Orange
name5
Date,Type
10/06/2015 15:05:14,Purple

我需要将格式更改为以下内容?有人可以推荐一种方式 这样做?:

name1,11/06/2015 18:13:42,Red
name2,08/06/2015 18:53:38,Blue
name3,10/06/2015 17:13:33,Yellow
name3,10/06/2015 17:55:11,Green
name4,15/06/2015 11:19:01,Blue
name4,10/06/2015 13:45:05,Orange
name5,10/06/2015 15:05:14,Purple

请注意,某些名称包含多个条目。

提前致谢!

1 个答案:

答案 0 :(得分:0)

  

此例程使用 Scripting.Dictionary 。您需要进入VBE的工具►参考,然后将 Microsoft Scripting Runtime 添加到项目中,然后才能使用它。

如果您可以将CSV作为活动工作簿打开,则此简短例程应重新组织您的数据。

Sub collate_CSV()
    Dim rw As Long, lr As Long, v As Long
    Dim dRECs As New Scripting.Dictionary
    Dim vKEY As Variant, vITM As Variant, vVALs As Variant

    dRECs.CompareMode = TextCompare
    ReDim vVALs(1 To 1)

    With Sheet1   '<-CSVs almost always have their single worksheet codename as Sheet1
        lr = .Cells(Rows.Count, 1).End(xlUp).Row
        For rw = lr To 2 Step -1
            Select Case LCase(.Cells(rw, 1).Value2)
                Case vbNullString
                    'do nothing
                Case "date,type"
                    ReDim Preserve vVALs(1 To UBound(vVALs) - 1)
                    dRECs.Add Key:=.Cells(rw - 1, 1).Value2, Item:=Join(vVALs, ChrW(8203))
                    ReDim vVALs(1 To 1)
                    .Cells(rw - 1, 1).Resize(Rows.Count - rw + 1, 1).EntireRow.Delete
                Case Else
                    vVALs(UBound(vVALs)) = .Cells(rw, 1).Value2
                    ReDim Preserve vVALs(1 To UBound(vVALs) + 1)
            End Select

        Next rw

        For Each vKEY In dRECs
            vITM = Split(dRECs.Item(vKEY), ChrW(8203))
            For v = LBound(vITM) To UBound(vITM)
                .Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = _
                  vKEY & Chr(44) & vITM(v)
            Next v
        Next vKEY

        .Rows(1).EntireRow.Delete

    End With

End Sub

您的结果应与以下内容类似:

Collate CSV with Scripting Dictionary

结果与原始结果相反。这是从数据底部进展到顶部的一个因素,随着工作的进展删除用过的记录。