【VBA】CSVファイルをエラー処理付きで転記する方法
手作業でのCSVファイルからExcelへのデータ移行は時間がかかり、ミスも起こりやすいです。この記事では、VBAを使用してエラー処理付きで簡単にデータを転記する方法を紹介します。
サンプルコード
VBA
Option Explicit
Sub CSVToExcel()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'CSVファイルの読み込み
Dim fPath As String, fData As Variant
fPath = "C:\path\to\yourfile.csv"
fData = Split(FileToString(fPath), vbCrLf)
'エラー処理
On Error GoTo ErrorHandler
Application.ScreenUpdating = False
Dim lastRow As Long, i As Long
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row + 1
For i = LBound(fData) To UBound(fData)
If fData(i) <> "" Then
ws.Cells(lastRow, 1).Value = Split(fData(i), ",")(0)
ws.Cells(lastRow, 2).Value = Split(fData(i), ",")(1)
lastRow = lastRow + 1
End If
Next i
Application.ScreenUpdating = True
MsgBox "CSVファイルの転記が完了しました。", vbInformation
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical
End Sub
Function FileToString(ByVal sFilePath As String) As String
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(sFilePath) Then
MsgBox "ファイルが存在しません。", vbExclamation
Exit Function
End If
FileToString = fso.OpenTextFile(sFilePath, 1).ReadAll
End Functionよくある質問
Q 元に戻せますか?
A.
VBAの実行結果は「元に戻す」が効きません。必ずバックアップを取ってから実行してください。
Q エラーが出たら?
A.
シート名や列番号が正しいか確認してください。