您好,欢迎访问三七文档
当前位置:首页 > 临时分类 > 把一个目录下的excel整合到一个文件中
操作要求:首先建立一个目录,将想要合并的表格放入到目录里,然后新建一个Excel文件--》打开--》Alt+F11--》插入模块--》将下面的程序考入--》然后回到文件里运行!SubCombineFiles()DimpathAsStringDimFileNameAsStringDimLastCellAsRangeDimWkbAsWorkbookDimWSAsWorksheetDimThisWBAsStringDimMyDirAsStringMyDir=ThisWorkbook.path&\'ChDriveLet't(MyDir,1)'findalltheexcelfiles'ChDirMyDir'Match=Dir$()ThisWB=ThisWorkbook.NameApplication.EnableEvents=FalseApplication.ScreenUpdating=Falsepath=MyDirFileName=Dir(path&\*.xls,vbNormal)DoUntilFileName=IfFileNameThisWBThenSetWkb=Workbooks.Open(FileName:=path&\&FileName)ForEachWSInWkb.WorksheetsSetLastCell=WS.Cells.SpecialCells(xlCellTypeLastCell)IfLastCell.Value=AndLastCell.Address=Range($A$1).AddressThenElseWS.CopyAfter:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)EndIfNextWSWkb.CloseFalseEndIfFileName=Dir()LoopApplication.EnableEvents=TrueApplication.ScreenUpdating=TrueSetWkb=NothingSetLastCell=NothingEndSub2、用microsoftexcel打开新建的excel表,并右键单击sheet1,找到“查看代码”,单击进去。进去之后就看到了宏计算界面。Sub合并当前目录下所有工作簿的全部工作表()DimMyPath,MyName,AWbNameDimWbAsWorkbook,WbNAsStringDimGAsLongDimNumAsLongDimBOXAsStringApplication.ScreenUpdating=FalseMyPath=ActiveWorkbook.PathMyName=Dir(MyPath&\&*.xls)AWbName=ActiveWorkbook.NameNum=0DoWhileMyNameIfMyNameAWbNameThenSetWb=Workbooks.Open(MyPath&\&MyName)Num=Num+1WithWorkbooks(1).ActiveSheet.Cells(.Range(B65536).End(xlUp).Row+2,1)=Left(MyName,Len(MyName)-4)ForG=1ToSheets.CountWb.Sheets(G).UsedRange.Copy.Cells(.Range(B65536).End(xlUp).Row+1,1)NextWbN=WbN&Chr(13)&Wb.NameWb.CloseFalseEndWithEndIfMyName=DirLoopRange(B1).SelectApplication.ScreenUpdating=TrueMsgBox共合并了&Num&个工作薄下的全部工作表。如下:&Chr(13)&WbN,vbInformation,提示EndSub
本文标题:把一个目录下的excel整合到一个文件中
链接地址:https://www.777doc.com/doc-2369676 .html