
フォルダ内にある大量のcsvファイルを結合するサンプルを載せておくよ!コピペなどで活用してね!



このように事前にフォルダ内へ結合したcsvファイルを集結しておいてください!


目次
大量のcsvファイル結合 サンプル
こちらのサンプルコードを実行すると、指定したフォルダ内にある全てのcsvファイルを1つのcsvファイルに結合します。
ここでは指定したフォルダ内にcombine.csvというファイルが新たに出力されます。
Sub FileCombine()
Dim bkPath_Log As String
Dim check_CombineFile As String
Dim folder_Path As String
Dim csvFile As String
Dim buf As String
'対象フォルダを指定
MsgBox " csvファイルを結合するよ! csvファイルが入ったフォルダを選択してね(^o^)"
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = True Then
folder_Path = .SelectedItems(1)
Else
MsgBox "フォルダが正しく選択されなかったので終了します(#^ω^)"
Exit Sub
End If
End With
'事前にcombine.csvが存在するか確認
check_CombineFile = Dir(folder_Path & "\*.csv")
Do While check_CombineFile <> ""
If check_CombineFile = "combine.csv" Then
MsgBox "既に「combine.csv」ファイルが存在するため終了します"
Exit Sub
End If
check_CombineFile = Dir()
Loop
'csvファイルが存在しない場合終了
bkPath_Log = Dir(folder_Path & "\*.csv")
If bkPath_Log = "" Then
MsgBox "ファイルが存在しません(ノД`)シクシク"
Exit Sub
End If
csvFile = folder_Path & "\combine.csv"
'新規csvファイルを作成
Open csvFile For Append As #1
'ファイルが存在する限り
Do While Len(bkPath_Log) > 0
'ファイルをOpenして追記
If bkPath_Log <> "combine.csv" Then
Open folder_Path & "\" & bkPath_Log For Input As #2
Do Until EOF(2)
Line Input #2, buf
Print #1, buf
Loop
Close #2
End If
'Dir関数で次のファイルへ
bkPath_Log = Dir()
Loop
Close #1
MsgBox "combine.csvにcsvファイルを結合しました(`・ω・´)ゞ"
End Sub
このように新たにcombine.csvファイルが出力されます。


まとめ
一度このサンプルをボタン登録しておくといつでもcsvファイルの結合が自動化できます。
この記事がミス撲滅や生産性向上につながるととても嬉しいです。
VBA初級から抜け出すための知恵と、実務で活用できるスキルが学べる1冊です!激しくオススメ!


\ Excel VBA技術書も豊富 /
コメント