将CSV导入Excel

我需要将一些CSV导入到Excel电子表格中,每个CSV的行/列号是不同的。 问题是有些值是长数字string
341235387313289173719237217391

Excel会将这些值视为(双)数字,然后导致数据丢失。

我的解决方法是使用以下vba函数来完成这项工作:

 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 

问题是性能。 它比通过Data-> From Text导入数据要慢得多,或者直接打开CSV。

有没有办法更有效地做到这一点?

您可以一次格式化/写入每一行:

 Sub readCSV(f As TextStream, sh As Worksheet) Dim i As Long Dim ss, l i = 1 With Application .ScreenUpdating = False .Calculation = xlCalculationManual End With 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, """,""") With sh.Cells(i, 1).Resize(1, (UBound(ss) - LBound(ss)) + 1) If (i-1) Mod 100 = 0 Then .Resize(100).NumberFormat = "@" .Value = ss End With i = i + 1 Loop Until f.AtEndOfStream With Application .ScreenUpdating = True .Calculation = xlCalculationAutomatic End With End Sub 

编辑 :经过testing,真正的性能杀手将单元格格式设置为文本修改代码,以100行代替每行代码块。

您可以使用正则expression式来快速创buildCSV文件的第二个版本,而不是使用Excel(通过单元格或按行)工作,而同时使用超过16个字符的string,

然后只需在Excel中导入或打开整个新的csv

在CSV文件上运行的示例代码StrIn以此path为例, "c:\Temp\test.csv"

 Sub Main() Dim objFSO As Object Dim objRegex As Object Dim objTF As Object Dim objTF2 As Object Dim tf As Object Dim strIn As String Dim strOut As String Dim strFile As String strIn = "c:\Temp\test.csv" strOut = "c:\Temp\test2.csv" Set objFSO = CreateObject("scripting.filesystemobject") Set objTF = objFSO.getfile(strIn) Set objRegex = CreateObject("vbscript.regexp") Set tf = objTF.OpenAsTextStream(ForReading) strFile = tf.ReadAll With objRegex .Pattern = "(\w{16,})" .Global = True strFile = .Replace(strFile, "'" & "$1") End With Set objTF2 = objFSO.OpenTextFile(strOut, ForWriting, True) objTF2.Write strFile objTF2.Close tf.Close End Sub 

尝试.Value = "'" & ss(j)

'强制值显示为Excel中的文本string。

另外,尝试在一个string中声明你的ss数组,以便在分割之后不会将这些数字存储为long。 就像是:

 Dim ss() as String = Split(l, """,""")