0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Posted at

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?