将许多Excel文件合并为一个

时间:2014-11-14 20:27:56

标签: excel merge

我正在寻找一种方法将许多Excel文件合并为一个。

我有超过10个具有相同数量的列和类似信息的文件。我知道我可以打开所有这些并复制并粘贴到一个,但我正在寻找一种更快的方法。

我也知道我可以将它们更改为.csv文件,并使用cmd命令将它们合并为一个。

我想要一种方法来完成它而不必打开所有这些。

1 个答案:

答案 0 :(得分:0)

你还没有说过,每个文件只有一张纸。无论如何,假设它只是一个(并且始终是第一个),您可以使用下面的代码。请替换" C:\ MyDirectory \ MyFiles"使用保存文件的文件夹的相应路径。

注意:文件打开程序不是我的工作。我在这里得到了帮助: http://software-solutions-online.com/2014/03/05/list-files-and-folders-in-a-directory/

希望这会有所帮助......



'note: the file opening procedure is not my work. I got help here:
'http://software-solutions-online.com/2014/03/05/list-files-and-folders-in-a-directory/

Sub Merge_Files()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Long
Dim col_no As Long, row_no As Long
Dim arr_ws As Variant
Dim ws1 As Worksheet, wb1 As Workbook
Dim col_ws1 As Long, row_ws1 As Long

Set wb1 = ThisWorkbook
Set ws1 = ActiveSheet

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("C:\MyDirectory\MyFiles")
i = 0
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
    i = i + 1
    Workbooks.Open Filename:=objFile
    row_no = ActiveSheet.Range(Cells(Rows.Count, 1), Cells(Rows.Count, 1)).End(xlUp).Row
    col_no = ActiveSheet.Range(Cells(1, Columns.Count), Cells(1, Columns.Count)).End(xlToLeft).Column
    arr_ws = ActiveSheet.Range(Cells(1, 1), Cells(row_no, col_no))
    ActiveWorkbook.Close savechanges = no
    ws1.Activate
        If ws1.Range("A1").Value <> "" Then
            row_ws1 = ActiveSheet.Range(Cells(Rows.Count, 1), Cells(Rows.Count, 1)).End(xlUp).Row + 1
            col_ws1 = ActiveSheet.Range(Cells(1, Columns.Count), Cells(1, Columns.Count)).End(xlToLeft).Column
        Else
            row_ws1 = 1
            col_ws1 = 1
        End If
    ws1.Range(Cells(row_ws1, 1), Cells(row_ws1 + row_no - 1, col_no)) = arr_ws
    
Next objFile
End Sub
&#13;
&#13;
&#13;