【VBA】CSVファイルを確認メッセージを出さずに取得する方法
毎回同じCSVファイルを取り込むのに、Excelが確認メッセージを表示するのは面倒ですよね。この記事では、その確認メッセージを出さずにスムーズにCSVファイルを取り込む方法をお伝えします。
サンプルコード
VBA
Option Explicit
Sub ImportCSVWithoutAlert()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
' CSVファイルのパス
Dim csvFilePath As String
csvFilePath = "C:\path\to\yourfile.csv"
Application.DisplayAlerts = False ' 確認メッセージを非表示にする
ws.QueryTables.Add(Connection:="TEXT;" & csvFilePath, Destination:=ws.Range("A1"))
With ws.QueryTables(1)
.Name = "MyCSV"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = False
.WebSingleBlockTextLoop = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False ' CSVファイルを取得する
End With
Application.DisplayAlerts = True ' 確認メッセージの表示を再開
End Subよくある質問
Q 元に戻せますか?
A.
VBAの実行結果は「元に戻す」が効きません。必ずバックアップを取ってから実行してください。
Q エラーが出たら?
A.
シート名や列番号が正しいか確認してください。