|
Sub 合并目录下所有工作簿()
Dim MyPath, MyName, AWbName
Dim Wb As Workbook, WbN As String
Dim G As Long
Dim Num As Long
Dim BOX As String
Application.ScreenUpdating = False
wjj = InputBox("请输入文件夹名称", "默认文件夹", "拆分文件") '需汇总的文件夹
If wjj = "" Then Exit Sub
MyPath = ThisWorkbook.Path & "\" & wjj
If Len(Dir(MyPath, vbDirectory)) = 0 Then MkDir MyPath 'vbDirectory文件夹 MkDir创建目录或文件夹
MyName = Dir(MyPath & "\" & "*.xls*")
AWbName = ActiveWorkbook.Name
With Sheets("汇总表")
MaxRow = .UsedRange.Rows.Count
If MaxRow > 3 Then
.Range("A4:E" & MaxRow).ClearContents '删除原表头下数据
End If
End With
Num = 0
Do While MyName <> ""
If MyName <> AWbName Then
Set Wb = Workbooks.Open(MyPath & "\" & MyName)
Num = Num + 1
With Workbooks(1).ActiveSheet
'For G = 1 To Sheets.Count
MaxRow1 = .UsedRange.Rows.Count
ActiveSheet.Range("A4:E" & MaxRow1).Copy .Cells(.Range("B65536").End(xlUp).Row + 1, 1)
'Next
WbN = WbN & Chr(13) & Wb.Name
Wb.Close False
End With
End If
MyName = Dir
Loop
MaxRow2 = Sheets("汇总表").Range("A3").End(xlDown).Row '行数
Sheets("汇总表").Activate
Cells(MaxRow2 + 1, 1).Value = "合计"
Cells(MaxRow2 + 1, 2).Value = Application.WorksheetFunction.Sum(Range(Cells(4, 2), Cells(MaxRow2 + 1, 2)))
Range("B1").Select
Application.ScreenUpdating = True
MsgBox "共合并了" & Num & "个工作薄如下:" & Chr(13) & WbN, vbInformation, "提示"
' 添加边框()
Range(Cells(3, 1), Cells(MaxRow2 + 1, 5)).Select
With Selection.Borders
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
End Sub
自己写的太死了,麻烦老师看看如果标题行数和列数都有变化,如何优化代码,可以通用,谢谢!
|
|