2013-06-21 33 views
0

我有一個很大的csv文件(大約10,000行),爲了上傳,我需要適應新的佈局。Excel 2010通過插入新行來合併列

目前,它是在這樣的格式:

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,所以如果宏可能包括註釋行指定指定的列是在哪裏,那將是非常有益的。

+1

更好的你先試試吧,在這裏東山再起,當你遇到問題.. – matzone

+0

讓我再重新表述。我只知道VBA在「hello world」級別。 – user2487644

回答

0

這應該做你想要的東西。儘管我已經假設你的文件是製表符分隔的。 它使用要爲其添加對Microsoft Scripting Runtime的引用的FileSystemObject讀取文件,轉到工具>引用並確保它被選中。 我已經評論過它在哪裏尋找特定的列號,但它應該讓你知道該怎麼做。

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 
+0

有點困惑,直到我把它放在一張空白紙上。然後它就像一個魅力。謝謝! – user2487644