使用场景:假设有20个EXCEL表格,把每个表格中名称为"500kV","换流站","特高压"的Sheet页,分别合并到一个新的EXCEL表格的名称为"500kV","换流站","特高压"的Sheet页中
function 合并表格() {
//合并文件为C盘下面名为test的文件夹
var folderPath = "C:\\Users\\li_dawei\\Desktop\\周单\\36周离线\\";
var fileName = Dir(folderPath +"\\*.*");
if(fileName == ""){
alert("文件为空,无法执行");
}
//创建合并表格,如果合并文件存在会报错,这里没做校验删除
var newWork = Workbooks.Add();
//创建指定Sheet页名称的新Sheet页
var arr = ["500kV","换流站","特高压"];
//获取工作表对象
var ws = newWork.Worksheets;
//创建对应3个sheet页
var ws1 = ws.Add();
var ws2 = ws.Add();
var ws3 = ws.Add();
ws1.Name = arr[0];
ws2.Name = arr[1];
ws3.Name = arr[2];
var introw = 1;
var tgyrow = 1;
var hlzrow = 1;
var one = 1;
while(fileName != ""){
// 打开工作簿
var workBook = Workbooks.Open(folderPath + "\\" + fileName);
//获取打开的表格的Sheet页名称
var openworksheet = workBook.Worksheets;
var openworksheetcount = openworksheet.Count;
for(x = 1; x < openworksheetcount+1; x++){
var openworksheetname = openworksheet.Item(x).Name;
// 执行复制代码
//就一个Sheet页直接复制,后面的Sheet页从第二行开始复制
var lastCol = workBook.Worksheets(openworksheetname).Cells(1, workBook.Worksheets(openworksheetname).Columns.Count).End(xlToLeft).Column;
var lastRow = workBook.Worksheets(openworksheetname).Cells(workBook.Worksheets(openworksheetname).Rows.Count,1).End(xlUp).Row;
if(openworksheetname == "500kV"){
one = introw;
introw = 2;
}else if(openworksheetname == "特高压"){
one = tgyrow;
tgyrow = 2;
}else{
one = hlzrow;
hlzrow = 2;
}
var startRow = newWork.Worksheets(openworksheetname).Cells(newWork.Worksheets(openworksheetname).Rows.Count,1).End(xlUp).Row;
workBook.Worksheets(openworksheetname).Range(Cells(one,1),Cells(lastRow,lastCol)).Copy(newWork.Worksheets(openworksheetname).Cells(startRow+1, 1));
}
// 关闭工作簿
workBook.Close(true);
// 获取下一个文件
fileName = Dir();
}
//删除多余空白首行
newWork.Worksheets(arr[0]).Range("A1").EntireRow.Delete();
newWork.Worksheets(arr[1]).Range("A1").EntireRow.Delete();
newWork.Worksheets(arr[2]).Range("A1").EntireRow.Delete();
//保存合并表格至原文件夹
newWork.SaveAs(folderPath+"\\"+"合并表格"+".xlsx");
// //关闭表格
// alert("合并完成,合并表格与要合并的表格同目录下");
// newWork.Close(true);
}