使用macros合并CSV文件

任何想法如何合并* .csv文件从一个文件夹?

我有很多* .csv文件具有相同的结构(计数和列的标题),我需要将他们的内容合并到一个工作表。

我知道这并不难。 但是,当我从一个表中添加内容时,我需要添加具有表格名称的新列,从中复制这些数据。

请帮忙吗?

谢谢!

有几种方法来处理它(例如: SO 39045638 )

我个人使用类似于下面的.bat文件,其中loc是csv文件的目录。 但是,这并不处理删除聚合文件。 它也不处理重复的标题,所以你需要编辑最后的csv删除它们。

@ECHO OFF Set loc=C:\Test\ Copy %loc%*.csv %loc%\Aggregate.csv 

这似乎是一个很好的方法如何解决这个问题。 它合并所有csv文件的内容,并从第二个文件中删除标题! :)但是仍然需要添加源文件的名字来解决这个问题。

选项显式

Sub ImportCSV()

 Dim strSourcePath As String Dim strDestPath As String Dim strFile As String Dim strData As String Dim x As Variant Dim Cnt As Long Dim r As Long Dim c As Long Application.ScreenUpdating = False 'Change the path to the source folder accordingly strSourcePath = "C:\Path\" If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\" 'Change the path to the destination folder accordingly strDestPath = "C:\Path\" If Right(strDestPath, 1) <> "\" Then strDestPath = strDestPath & "\" strFile = Dir(strSourcePath & "*.csv") Do While Len(strFile) > 0 Cnt = Cnt + 1 If Cnt = 1 Then r = 1 Else r = Cells(Rows.Count, "A").End(xlUp).Row + 1 End If Open strSourcePath & strFile For Input As #1 If Cnt > 1 Then Line Input #1, strData End If Do Until EOF(1) Line Input #1, strData x = Split(strData, ",") For c = 0 To UBound(x) Cells(r, c + 1).Value = Trim(x(c)) Next c r = r + 1 Loop Close #1 Name strSourcePath & strFile As strDestPath & strFile strFile = Dir Loop Application.ScreenUpdating = True If Cnt = 0 Then _ MsgBox "No CSV files were found...", vbExclamation 

结束小组