使用宏合并CSV文件

时间:2016-08-24 14:28:57

标签: excel csv

知道如何合并一个文件夹中的* .csv文件吗?

我有许多具有相同结构的* .csv文件(列的数量和标题),我需要将它们的内容合并到一张表中。

我知道,这并不难。但是当我从一个表中添加内容时,我需要添加一个新列,其中包含我从中复制此数据的表名。

请帮忙吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

有几种方法可以接近它(例如:SO 39045638

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

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

答案 1 :(得分:0)

这似乎是一个很好的方法如何解决这个问题。它合并所有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

End Sub

相关问题