将CSV导入Excel

时间:2012-08-08 23:47:24

标签: excel vba csv data-import

我需要将一些CSV导入Excel电子表格,每个CSV的行/列号都不同。问题是某些值是长数字字符串,如
341235387313289173719237217391

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

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

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。

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

3 个答案:

答案 0 :(得分:2)

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

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

编辑:经过测试,真正的性能杀手是将单元格格式设置为文本修订代码,将其设置为100行而不是每行。

答案 1 :(得分:1)

您可以使用Regexp快速创建CSV文件的第二个版本,而不是使用前一个{{1}更新超过16个字符的alpantring of alpanumerics,而不是在Excel中工作(按单元格或按行) }

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

在CSV文件'上运行的示例代码,示例为StrIn

"c:\Temp\test.csv"

答案 2 :(得分:0)

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

'强制值在Excel中显示为文本字符串。

另外,尝试在字符串中声明你的ss数组,这样它就不会在分割后存储数字。类似的东西:

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