Domanda

I have a large csv file (about 10,000 rows) that I need to adapt to a new layout for the sake of uploading.

It is currently in a format like this:

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

into something that looks like this.

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

I understand VBA only on a base level, and the columns are not necessarily A B C D, so if the macro could include comment lines to specify where the column is specified, it would be very helpful.

È stato utile?

Soluzione

This should do something like what you need. Though I have made the assumption your file is Tab delimited. It reads the file in using the FileSystemObject for which you'll need to add a reference to the Microsoft Scripting Runtime , go Tools > References and make sure it is checked. I've commented in where it is looking for specific column numbers but it should give you an idea of what to do.

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top