|
Pleae test
Sub 合并()
Application.DisplayAlerts = False
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(ThisWorkbook.Path)
For Each ff In f.Files
If ff.Name <> ThisWorkbook.Name Then
Kill ff
End If
Next ff
Set sf = f.SubFolders
For Each f1 In sf
For Each fff In f1.Files
If fff.Name Like "*.xls" Then
nfilename = "合并" & Replace(fff.Name, "xls", "") & xlsx '合并filename
Else
nfilename = "合并" & fff.Name '合并filename
End If
nfile = ThisWorkbook.Path & "\" & nfilename '合并file fullname
If fs.fileexists(nfile) = False Then
Workbooks.Add
Sheets(1).Name = "合并"
ActiveWorkbook.SaveAs nfile
Else
Workbooks.Open nfile
End If
Workbooks.Open fff 'source file
er = [a65536].End(xlUp).Row
ec = ActiveSheet.UsedRange.Columns.Count
tr = Workbooks(nfilename).Sheets("合并").[b65536].End(xlUp).Row + 1 '合并filename
If tr = 2 Then 'copy the title
tr = 1
ActiveSheet.Range(Cells(1, 1), Cells(1, ec)).Copy Workbooks(nfilename).Sheets("合并").Range("b1")
'Workbooks(nfilename).Sheets("合并").Range("a1") = fff
End If
tr = Workbooks(nfilename).Sheets("合并").[b65536].End(xlUp).Row + 1 '合并filename
'数据缺失
If er = 1 Then
Workbooks(nfilename).Sheets("合并").Range("a" & tr) = fff
Workbooks(nfilename).Sheets("合并").Range("b" & tr) = "数据缺失"
Else
ActiveSheet.UsedRange.Copy Workbooks(nfilename).Sheets("合并").Range("b" & tr)
Workbooks(nfilename).Sheets("合并").Range("a" & tr & ":a" & tr + er - 1) = fff
Workbooks(nfilename).Sheets("合并").Rows(tr).Delete
End If
ActiveWorkbook.Close False
Workbooks(nfilename).Close True
Next
Next
Application.DisplayAlerts = True
End Sub |
|