goo blog サービス終了のお知らせ 

半角チルダ

ExcelVBA、その他。
覚え書きや、補足資料などのスクラップブック。
end-u(1037781)

■複数CSVファイルのまとめ

2008-02-05 20:00:00 | VBA Tips
Copyコマンドを使ってCSVファイルを結合する。

Sub try1()
    Const CRFILE As String = "D:¥ketugou.csv"
    Dim arg As String

    arg = ThisWorkbook.Path & "¥*.csv "
    Call Shell(Environ("ComSpec") & " /c copy /b " & arg & CRFILE)
End Sub

シート上に読み込んでまとめる。

Sub try2()
  Dim fd As String
  Dim fn As String
  Dim ret As String
  Dim n  As Long
  Dim x  As Long
  Dim i  As Long
  Dim j  As Long

  Application.ScreenUpdating = False
  fd = ThisWorkbook.Path & "¥"
  'Dir関数を使って指定フォルダ内csvファイルを順次処理
  fn = Dir(fd & "*.csv")
  n = 1
  x = 1
  On Error GoTo errHndler
  'ActiveWorkbookにシートを追加して処理
  With Sheets.Add
    Do Until Len(fn) = 0&
      i = i + 1
      '外部データ取り込みを利用
      With .QueryTables.Add(Connection:="TEXT;" & fd & fn, _
                 Destination:=.Cells(n, 2))
        .AdjustColumnWidth = False
        .TextFilePlatform = xlWindows
        .TextFileStartRow = x
        .TextFileCommaDelimiter = True
        .Refresh False
        j = .ResultRange.Rows.Count
        .Parent.Names(.Name).Delete
        .Delete
      End With
      'ファイル名をA列にセット
      .Cells(n, 1).Resize(j).Value = fn
      n = n + j
      'x = 2 '2ファイル以降2行目
      fn = Dir()
    Loop
  End With
  If i > 0 Then
    ret = i & "files.done"
  Else
    ret = "no file"
  End If
errHndler:
  If Err.Number <> 0 Then ret = Err.Number & ":" & Err.Description
  Application.ScreenUpdating = True
  MsgBox ret
End Sub

#とりあえずオーソドックスな手法。1シート読み込み可能な行数を超えるケースは考慮せず。

Comment    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« ■[EnableAutoFilter プロパティ] | TOP | ■QueryTables.Add/.Deleteと.... »
最新の画像もっと見る

Recent Entries | VBA Tips