首页 > Excel专区 > Excel函数 >

EXCEL VBA 跨表合并多个文件

Excel函数 2022-02-16 20:58:57

‘选择一个目录,将目录中的所有EXCEL文件导入当前工作表

‘这些EXCEL文件最好格式能一样,这里是每个文件是同一个格式

Sub 批量()
Dim FD, str$, arr
Set FD = Application.FileDialog(msoFileDialogFolderPicker)
If FD.Show = -1 Then t = FD.SelectedItems(1) Else Exit Sub ‘如果没选择文件夹则退出
Application.ScreenUpdating = False
Cells.NumberFormatLocal = "@"
str = Dir(t & "\*.xl*") ‘查找格式为EXCEL的文件
While Len(str) > 0 ‘文件名不为空时
Workbooks.Open (t & IIf(Right(t, 1) = "", "", "") & str) ‘打开工作簿

With ActiveWorkbook.ActiveSheet
.Range(.Cells(2, "l"), .Cells(.[a65536].End(3).Row, "l")) = "’" & Left(str, Len(str) – IIf(Right(str, 1) = "x", 5, 4))
arr = .UsedRange
Workbooks(str).Close False ‘关闭工作薄

Kill (t & IIf(Right(t, 1) = "", "", "") & str) ’删除工作薄(如果不删除,省去这一步)

End With

With ActiveSheet
rw = .[a65536].End(3).Row + 1
.Cells(rw, 1).Resize(UBound(arr, 1), UBound(arr, 2)) = arr ‘将数据写入当前工作表
End With
str = Dir() ‘查找下一个文件
Wend
If [a1] = "" Then Rows(1).Delete ‘如果A1为空,删除第一行
Application.ScreenUpdating = True
End Sub


标签: 删除工作批量文件excel函数

office教程网 Copyright © 2016-2020 http://www.office9.cn. Some Rights Reserved. 苏ICP备20040415号-9