逐行讀取CSV文件一行到一個數組是10,000行通過100列。當數組已滿時,我將它寫入Excel,重新設置數組並繼續,直到文件結束。
我最初嘗試使用動態數組,但它會凍結Excel。使用靜態數組實際上更有效。
您需要調整常數值。從你的圖像看起來你的文件是分號分隔的。如果ColumnCount
只要大於或等於實際列數,那麼確實如此。
Const CSVFileName = "C:\Users\best buy\Downloads\stackoverfow\Sample Data File\R58K x C60.csv"
Const Delimiter = ","
Const PageSize = 10000
Const ColumnCount = 100
導入100,000行和64列大約需要32秒。 CSV文件在磁盤上爲69.5 MB。
Option Explicit
Sub ProcessFile()
Const CSVFileName = "C:\Users\best buy\Downloads\stackoverfow\Sample Data File\R58K x C60.csv"
Const Delimiter = ","
ActiveSheet.DisplayPageBreaks = False
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Debug.Print Now
Dim Start: Start = Timer
Dim lastRow As Long
Dim arFormulas
arFormulas = Range("A1:C1").Formula
Columns("A:BF").ClearContents
ImportCSVFile CSVFileName, Delimiter
Debug.Print "Time to import CSV file in seconds:"; Timer - Start
Start = Timer
lastRow = Cells(Rows.Count, "D").End(xlUp).Row
Range("A1:C" & lastRow).Formula = arFormulas
Debug.Print "Time to add formulas in seconds:"; Timer - Start
Debug.Print "Column Count:"; Worksheets("Sheet1").UsedRange.Columns.Count
Debug.Print "Row Count:"; Worksheets("Sheet1").UsedRange.Rows.Count
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
.AutoRecover.Enabled = True
End With
End Sub
Sub ImportCSVFile(FilePath As String, Delimiter As String)
Const PageSize = 10000
Const ColumnCount = 100
Dim line As String
Dim arData, arLine
Dim x As Long, y As Long, z As Long
ReDim arData(PageSize, ColumnCount)
z = 1
Open FilePath For Input As #1 ' Open file for input
Do While Not EOF(1) ' Loop until end of file
Line Input #1, line
arLine = Split(line, Delimiter)
y = 0
For y = 0 To UBound(arLine)
arData(x, y) = arLine(y)
Next
x = x + 1
If x = PageSize Or EOF(1) Then
Range("D" & z).Resize(x, y) = arData
z = z + x
ReDim arData(PageSize, ColumnCount)
x = 0
End If
Loop
Close #1
Erase arData
End Sub
#felipe31你確定你的代碼?!?!?你選擇單元格(「D:BF」),並清除那些,那麼LastRow將是D1! – Fabrizio
@Fabrizio OP在導入新數據之前清除舊數據。 – 2016-08-24 06:21:51
@ThomasInzina是對的 – felipe31