Sub LoadCSVWithPowerQuery()
Dim csvPath As String
Dim queryName As String
Dim ws As Worksheet
Dim lo As ListObject
' 読み込むCSVファイルのパス(適宜変更)
csvPath = Application.GetOpenFilename("CSV Files (*.csv), *.csv", , "CSVファイルを選択してください")
If csvPath = "False" Then Exit Sub ' キャンセル時
' クエリ名をファイル名から生成
queryName = "Query_" & Replace(Replace(Dir(csvPath), ".", "_"), " ", "_")
' クエリ追加(Power Query でCSVを読み込み)
ThisWorkbook.Queries.Add Name:=queryName, Formula:= _
"let" & vbCrLf & _
" Source = Csv.Document(File.Contents(""" & csvPath & """),[Delimiter="","", Columns=999, Encoding=65001, QuoteStyle=QuoteStyle.None])," & vbCrLf & _
" PromotedHeaders = Table.PromoteHeaders(Source, [IgnoreErrors=true])" & vbCrLf & _
"in" & vbCrLf & _
" PromotedHeaders"
' 新しいシートを作ってクエリを読み込み
Set ws = ThisWorkbook.Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "元データ"
' 読み込んだクエリをワークシートにロード
With ws.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & queryName & ";Extended Properties=""""" _
, Destination:=ws.Range("A1"))
.Name = "CSVTable"
.QueryTable.CommandType = xlCmdSql
.QueryTable.CommandText = Array("SELECT * FROM [" & queryName & "]")
.QueryTable.Refresh BackgroundQuery:=False
End With
End Sub