把文件夹中N个表格Sheet1页的数据合并成一个新的表格
function 合并表格() {
//合并文件为C盘下面名为test的文件夹
var folderPath = "C:\\test";
var fileName = Dir(folderPath +"\\*.*");
if(fileName == ""){
alert("文件为空,无法执行");
}
//创建合并表格,如果合并文件存在会报错,这里没做校验删除
var newWork = Workbooks.Add();
while(fileName != ""){
// 打开工作簿
var workBook = Workbooks.Open(folderPath + "\\" + fileName);
// 执行复制代码
//默认合并每个表格的Sheet1页
var lastCol = workBook.Worksheets("Sheet1").Cells(1, workBook.Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column;
var lastRow = workBook.Worksheets("Sheet1").Cells(workBook.Worksheets("Sheet1").Rows.Count,1).End(xlUp).Row;
//获取合并页的有多少行
var startRow = newWork.Worksheets("Sheet1").Cells(newWork.Worksheets("Sheet1").Rows.Count,1).End(xlUp).Row;
//开始复制
workBook.Worksheets("Sheet1").Range(Cells(1,1),Cells(lastRow,lastCol)).Copy(newWork.Worksheets("Sheet1").Cells(startRow+1, 1));
// 关闭工作簿
workBook.Close(true);
// 获取下一个文件,Dir()方法不给任何参数,默认去找下一个匹配的文件
fileName = Dir();
}
//删除多余的首行
newWork.Worksheets("Sheet1").Range("A1").EntireRow.Delete();
//保存合并表格至原文件夹
newWork.SaveAs(folderPath+"\\"+"合并表格"+".xlsx");
//关闭表格
alert("合并完成,合并表格与要合并的表格同目录下");
newWork.Close(true);
}