2016-08-24 48 views
0

任何想法如何合并来自一个文件夹的* .csv文件?使用宏合并CSV文件

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

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

请帮忙吗?

谢谢!

+0

这将在Python是容易得多,虽然IM假设你只是想用VBA来做到这一点? –

+0

考虑到你首先必须安装Python,我不认为这会更容易。当你只有一把锤子时,所有东西看起来都像钉子。考虑@Kevin答案的简单性...... –

+0

我必须在VBA中做到这一点,这就是问题所在。这对于商业用户来说必须是简单的“工具”。 – Vestyak

回答

0

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

末次

+0

感谢您的好提示:) – Vestyak

1

有几种方法可以解决它(例如:SO 39045638

我个人使用类似于下面,.bat文件,其中LOC是为CSV文件的目录。不过,这并不处理删除汇总文件。它也不处理重复标题,因此您需要编辑最终的csv以将其删除。

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

嗨凯文,我同意你的意见。我以同样的方式做到了,但对于商业用户来说,启动bat文件似乎很困难:)所以它必须是整个操作的一个宏。 – Vestyak

+0

以何种方式比运行宏更难以双击bat文件?请具体说明,这允许用户在提出答案之前了解所有限制 –