我有一个大的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,并且列不一定是A B C D,因此如果宏可以包含注释行来指定列的指定位置,那将非常有用。
答案 0 :(得分:0)
这应该做你需要的事情。虽然我假设您的文件是制表符分隔符。 它使用FileSystemObject读取文件,您需要为其添加对Microsoft Scripting Runtime的引用,go Tools>引用并确保已选中。 我已经评论了它在哪里寻找特定的列号,但它应该让你知道该怎么做。
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