使用宏合并CSV文件

Vestyak

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

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

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

有什么帮助吗?

谢谢!

Vestyak

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

显式期权

子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

结束子

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章