VBAでフォルダ内のCSVファイルを取り込む方法
「C:\tmp\」配下にある「*.csv」のファイルをファイル名でExcelのワークシートを作成します。
CSVファイルの内容
1,いるか,うみ 2,うさぎ,りく
コード全体
Sub createWorkSheet() Dim targetPath As String Dim newSheet As Worksheet Dim dirPath As String dirPath = "C:\tmp\" Dim txtExtension As String txtExtension = "*.csv" targetPath = Dir(dirPath & txtExtension) Do While targetPath <> "" Worksheets.Add After:=Worksheets(Worksheets.Count) ActiveSheet.Name = targetPath csvSplit (dirPath & targetPath) targetPath = Dir() Loop End Sub Function csvSplit(ByVal targetPath As String) Dim columNumber As Long Dim rowNumber As Long rowNumber = 1 Dim buf As String Dim strArray As Variant Open targetPath For Input As #1 Do Until EOF(1) Line Input #1, buf strArray = Split(buf, ",") For columNumber = 0 To UBound(strArray) Cells(rowNumber, columNumber + 1) = strArray(columNumber) Next rowNumber = rowNumber + 1 Loop Close #1 End Function
コメント