I need to import some CSVs into Excel spreadsheet, the row/column numbers of the CSVs are different for each of them. The problem is that some values are long digit strings like
341235387313289173719237217391,
Excel will treat those values as (double) numbers, and then results in lost of data.
My way to solve it is to use the following vbafunction to do the job:
Sub readCSV(f As TextStream, sh As Worksheet)
i = 1
Do
l = Trim(f.ReadLine)
If l = "" Then Exit Sub 'skip the last empty line(s)
l = Mid(l, 2, Len(l) - 1)
ss = Split(l, """,""")
For j = LBound(ss) To UBound(ss) 'j starts from 0
Dim a As Range
With sh.Cells(i, j + 1)
.NumberFormat = "@" 'Force to text format
.Value = ss(j)
End With
DoEvents 'Avoid blocking the GUI
Next j
i = i + 1
Loop Until f.AtEndOfStream
End Sub
The problem is the performance. It is much slower than importing the data through Data->From Text or just open the CSVs directly.
Are there any way to do it more efficiently?
You can format/write each line in one shot:
EDIT: after testing, the real performance killer is setting the cell format to text- revised code to set this in blocks of 100 lines instead of each line.