更改VBA CreateObject(" Scripting.FileSystemObject")。OpenTextFile(filename).ReadAll到更低的内存占用

时间:2017-06-11 22:05:34

标签: excel vba excel-vba

所以我有一个巨大的CSV文件,在加载到Excel电子表格之前必须进行转置(由于Excel 2010的限制)。在文件变大(> 30mb)之前,这段代码似乎可以解决问题。

Sub transpose_delimited_file(sheet, filename, skip_columns, delimiter)
Dim temp As String
Dim i As Long, x


temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(filename, 1).ReadAll
x = Split(temp, vbCrLf): temp = ""
For i = 0 To UBound(x) - 1
    y = Split(x(i), delimiter)
    ThisWorkbook.Sheets(sheet).Cells(1, i + 1 + skip_columns).Resize(UBound(y) + 1).Value = _
    Application.Transpose(y)
Next

那么如何更改上面的代码以避免内存不足错误?有没有办法将ReadAll更改为一次只读取X行数然后转置并粘贴到工作表中以保持内存空闲?非常感谢。

1 个答案:

答案 0 :(得分:2)

最佳尝试是逐行读取文件并将其粘贴为目标工作表中的列。以下使用原始I / O的代码应该实现它:

Sub transposeDelimitedFile(ByRef sh As Worksheet, ByVal fName As String, _
                           Optional ByVal startCol As Long = 1, _
                           Optional ByVal delim As String = ",")
  Dim sLine As String, ar

  Open fName For Input As #1
  Do Until EOF(1)
    Line Input #1, sLine
    ar = Split(sLine, delim)
    sh.Columns(startCol).Resize(UBound(ar) + 1).value = Application.Transpose(ar)
    startCol = startCol + 1
  Loop
  Close #1
End Sub
Sub Test()
  transposeDelimitedFile Worksheets("Sheet1"), "C:\SO\SO.CSV", 6, ","
End Sub