新建一个BOOK文件,同时按Alt+F11这二个键,进入VBA编辑界面,点击编辑画面的菜单:“插入”--“模块”,然后在里面完整复制下面的代码:
Sub 同一
文件夹多xls合并()
'Sub mergeonexls() '合并多工作簿中指定工作
表 On Error Resume Next
Dim x As Variant, x1 As Variant, w As Workbook, wsh As Worksheet
Dim t As Workbook, ts As Worksheet, l As Integer, h As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
x = Application.GetOpenFilename(FileFilter:="Excel文件 (*.xls; *.xlsx),*.xls; *.xlsx,所有文件(*.*),*.*", _
Title:="Excel选择", MultiSelect:=True)
Set t = ThisWorkbook
Set ts = t.Sheets(1) '指定合并到的工作表,这里是第一张工作表
l = ts.UsedRange.SpecialCells(xlCellTypeLastCell).Column
For Each x1 In x
If x1 <> False Then
Set w = Workbooks.Open(x1)
Set wsh = w.Sheets(1) '指定所需合并工作表,这里是第一张工作表
h = ts.UsedRange.SpecialCells(xlCellTypeLastCell).Row
If l = 1 And h = 1 And ts.Cells(1, 1) = "" Then
wsh.UsedRange.Copy ts.Cells(1, 1)
Else
wsh.UsedRange.Copy ts.Cells(h + 1, 1)
End If
w.Close
End If
Next
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
请关闭编辑画面回到工作表,点击菜单:工具--宏,或直接按ALT+F8组合键,在框中选择“同一文件夹多xls合并”,点“执行”,开始选择你想合并的工作簿,请按住CTRL键再用鼠标多个工作簿点击选取,最后点击“打开”,这样就完成合并。本回答被提问者采纳