发布于 2023-10-31 09:47:37 浏览 129 次
Sub MergeFiles()
Dim FolderPath As String
Dim FileName As String
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim wsDestination As Worksheet
Dim LastRow As Long
' 设置合并文件的目标工作表
Set wsDestination = ThisWorkbook.Worksheets("Sheet1") ' 将 "Sheet1" 替换为实际的工作表名称
' 设置源文件所在的文件夹路径
FolderPath = "C:\路径\至\文件夹\" ' 替换为实际的文件夹路径
' 循环遍历文件夹中的所有Excel文件
FileName = Dir(FolderPath & "*.xlsx")
Do While FileName <> ""
' 打开源文件
Set wbSource = Workbooks.Open(FolderPath & FileName)
' 复制源文件的数据到目标工作表
Set wsSource = wbSource.Worksheets(1) ' 可能需要调整工作表的索引,根据实际情况调整
LastRow = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Row
wsSource.UsedRange.Copy Destination:=wsDestination.Cells(LastRow + 1, 1)
' 关闭源文件,并释放内存
wbSource.Close SaveChanges:=False
Set wbSource = Nothing
' 遍历下一个文件
FileName = Dir()
Loop
End Sub