[Excel VBA]CSVファイルを高速で読み込む
QueryTablesオブジェクトのAddメソッドを使う。まずは動作確認のための巨大なCSVファイル(qt.csv)を作成する。PowerShellで以下のコマンドを実行すると100万行からなるCSVファイル(ファイルサイズ11,000,000バイト(約10.5メガバイト))が作成される。
PS > "A,B,C,1,2`r`n" * 1000000 | Out-File -Encoding default -NoNewline qt.csv
PS > Get-ChildItem .\qt.csv
ディレクトリ: ○○○
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2023/07/01 22:33 11000000 qt.csv
PS > Get-Content -path .\qt.csv -TotalCount 3
A,B,C,1,2
A,B,C,1,2
A,B,C,1,2
以下のプログラムを実行する。ワークシートSheet1の中身を強制的にすべて削除し、A1セルからファイルの中身を強制的に入力するので注意。
Dim filepath As String
Dim ws As Worksheet
Dim qt As QueryTable
Dim dtstart As Date
Dim dtend As Date
filepath = Application.ThisWorkbook.Path & "\qt.csv"
Set ws = Worksheets("Sheet1")
ws.Cells.Clear
dtstart = Time
Debug.Print "開始時刻: " & dtstart
Set qt = ws.QueryTables.Add(Connection:="TEXT;" & filepath, Destination:=ws.Range("A1"))
With qt
.TextFileCommaDelimiter = True
.TextFileParseType = xlDelimited
.TextFilePlatform = 932
.RefreshStyle = xlOverwriteCells
.Refresh
.Delete
End With
dtend = Time
Debug.Print "終了時刻: " & dtend
Debug.Print "処理時間: " & DateDiff("s", dtstart, dtend) & "秒"
イミディエイトの出力
開始時刻: 23:26:05
終了時刻: 23:26:11
処理時間: 6秒
10.5メガバイトのCSVファイルを約6秒で読み込んで各セルに入力していることが分かる。