'CSVファイルを取り込む
Sub ImportUTF8CSV()
Dim connection As Object
Dim resultSet As Object
Dim filePath As String
Dim sheetName As String
Dim query As String
'ファイル選択ダイアログを表示してCSVファイルを選択
filePath = Application.GetOpenFilename("CSVファイル (*.csv), *.csv", , "CSVファイルを選択してください")
' ファイル選択がキャンセルされた場合は処理を終了
If filePath = "False" Then Exit Sub
' データを貼り付けるシート名を指定
sheetName = "Sheet1"
' ADODB.Connectionオブジェクトを作成
Set connection = CreateObject("ADODB.Connection")
' ADODB.Recordsetオブジェクトを作成
Set resultSet = CreateObject("ADODB.Recordset")
' CSVファイルへの接続文字列を設定(ヘッダーなし、区切り形式、UTF-8)
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Left(filePath, InStrRev(filePath, "\")) & ";" & _
"Extended Properties=""text;HDR=No;FMT=Delimited;CharacterSet=65001;"""
' 接続を開く
connection.Open
' クエリを設定([]のなかでファイルパスからファイル名だけを取ってきている。)
query = "SELECT * FROM [" & Mid(filePath, InStrRev(filePath, "\") + 1) & "]"
' クエリを実行してデータを取得(1:(CuresultSetorType)レコードの読み書きが可能で、削除されたレコードは認識できる、3:(LockType)更新が実際に行われるときにだけロックされます。)
resultSet.Open query, connection, 1, 3
' データをシートに貼り付け
ThisWorkbook.Sheets("Sheet1").Cells(1, 1).CopyFromRecordset resultSet
' 接続とレコードセットを閉じる
resultSet.Close
connection.Close
' オブジェクトを解放
Set resultSet = Nothing
Set connection = Nothing
ThisWorkbook.Save ' 現在のファイル名で保存
End Sub
‘‘‘
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme