🦝

【VBA】csvファイルの読み込み方

2021/07/05に公開

csvファイルの読み込み方

1. 読み込むcsvファイルを指定する

Sub selectFile()
	Dim filePath As String
        With Application.FileDialog(msoFileDialogFilePicker)
                With .Filters
                        .Clear
                        .Add "csvファイル", "*.csv"
                End With
                If .Show = True Then
                        filePath = .SelectedItems(1)
                Else: End
                End If
        End With
        Debug.Print "読み込みファイルパス " & filePath
End Sub

2. 指定したcsvファイルを新しいシートに読み込む

ThisWorkbook.Worksheets.Add
ActiveSheet.Name = "capture"

Dim buf As String, a As Variant, n As Long, m As Long
Open filePath For Input As #1
	Do Until EOF(1)
		n = n + 1
		Line Input #1, buf
		a = Split(Replace(buf, """", ""), ",")
		For m = 0 To UBound(a)
			Cells(n, m + 1) = a(m)
		Next m
	Loop
Close #1

csvファイルの列数が分かっている場合

高速化できる。多分

Dim buf As String, a As Variant, n As Long
Open filePath For Input As #1
	Do Until EOF(1)
		n = n + 1
		Line Input #1, buf
		Cells(n, 1).Resize(, 列数) = Split(Replace(buf, """", ""), ",")
	Loop
Close #1

Discussion