0

我有一个大的 csv 文件(大约 10,000 行),为了上传,我需要适应新的布局。

它目前的格式如下:

Index1 Title1 1,2,3,4 Option1 A,B     OtherData
Index2 Title2 1,2,3   Option2 A,B,C,D OtherData
Index3 blank  blank   blank   blank   OtherData
Index4 Title4 1,2     blank   blank   OtherData

变成这样的东西。

Index1 Title1 1 Option1 A             OtherData
              2         B
              3
              4

Index2 Title2 1 Option2 A             OtherData
              2         B
              3         C
                        D

Index3                                OtherData

Index4 Title4 1                       OtherData
              2

我仅在基本级别上了解 VBA,并且列不一定是 ABCD,因此如果宏可以包含注释行来指定指定列的位置,那将非常有帮助。

4

1 回答 1

0

这应该做一些你需要的事情。尽管我假设您的文件是制表符分隔的。它使用 FileSystemObject 读取文件,您需要为其添加对 Microsoft Scripting Runtime 的引用,转到 Tools > References 并确保它已被选中。我已经评论了它在哪里寻找特定的列号,但它应该让你知道该怎么做。

Dim fs As New FileSystemObject
Dim ts As TextStream
i = 0
Set ts = fs.OpenTextFile("file.csv")
While Not ts.AtEndOfStream
    textline = Split(ts.ReadLine, Chr(9))
    Range("a1").Offset(i).Resize(1, 6).Value = textline  'Assumes there are six columns in the    file
    NewCol1 = Split(textline(2), ",")       'Split the 3rd word into an array (2 as it's zero based)
    NewCol2 = Split(textline(4), ",")       'Split the 5rd word into an array
    RowCount1 = UBound(NewCol1)
    RowCount2 = UBound(NewCol2)
    MaxCount = IIf(RowCount1 > RowCount2, RowCount1, RowCount2) 'Find the largest of the two row    counters as we need to move down this many rows
    If RowCount1 > 0 Then Range("a1").Offset(i, 2).Resize(RowCount1 + 1, 1) = WorksheetFunction.Transpose(NewCol1)  'Put the array vertically in the 3rd column
    If RowCount2 > 0 Then Range("a1").Offset(i, 4).Resize(RowCount2 + 1, 1) = WorksheetFunction.Transpose(NewCol2) 'Put the array vertically in the 5th column (4 along from cell    A1)
    i = i + MaxCount + 1
Wend
于 2013-06-24T00:24:55.407 回答