表格存储各个省的信息,江苏的有50行数据,山西的55行数据等等,这个就是把江苏的创建一个新表保存,山西的创建一个新表格保存。里面主要是表格的创建与关闭相关知识,还有动态给表格对象赋值,实现循环操作表格的目的。
function JIn521() {
//设置工作表对象
var ws1 = ThisWorkbook.Worksheets('Sheet1');
//Sheet1页首列复制到Sheet2页并去重
var lastRow = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row;
var sheet1Range1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(lastRow, 1));
Worksheets.Add();
ActiveSheet.Name = "Sheet2"
var ws2 = ThisWorkbook.Worksheets('Sheet2');
sheet1Range1.Copy(ws2.Cells(1, 1));
ws2.Columns(1).EntireColumn.RemoveDuplicates(1, xlYes);
//D盘下面创建名为test的文件夹
var folderPath = "C:\\test";
while(Dir(folderPath +"\\*.*") != ""){
Kill(folderPath + "\\*.*");
}
if(Dir(folderPath,16)!=""){
RmDir(folderPath);
alert("test文件已存在,已执行删除后重建");
MkDir(folderPath);
}else{
MkDir(folderPath);
}
//遍历Sheet2页值创建其余表格
var st2lastRow = ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row;
var workObjects = {};
for(var z = 0; z<st2lastRow-1;z++){
var sheet2Range2ItemValue = ws2.Cells(z+2, 1).Value2;
var newWork = Workbooks.Add();
var date = new Date().toLocaleString();
var date1 = date.split(" ");
var date2 = date1[0].replace(/\//g, ".");
newWork.SaveAs(folderPath+"\\"+sheet2Range2ItemValue+"_"+date2+".xlsx");
workObjects[sheet2Range2ItemValue] = newWork;
//Sheet1页复制到其他表格Sheet1页
var lastCol = ws1.Cells(1, ws1.Columns.Count).End(xlToLeft).Column;
var sheet1Range2 = ws1.Range(ws1.Cells(1,1),ws1.Cells(lastRow,lastCol));
sheet1Range2.Copy(workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Cells(1, 1));
//获取其他页数据及地址
var arrow = new Array();
var st5LastRow = workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Cells(workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Rows.Count, 1).End(xlUp).Row;
for(var j = 0 ; j < st5LastRow ; j++){
arrow[j]=j+1;
}
var arrow1 = new Array();
for (let x = 0; x < arrow.length; x++) {
var a = workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Range("A"+arrow[x]).Value2;
var b = workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Range("A"+arrow[x]).Address();
arrow1.push(a+":"+b);
}
//遍历删除各个地市
for(let i = 0;i<arrow1.length;i++){
array = arrow1[i].split(':');
if(array[0] != sheet2Range2ItemValue && array[0]!= "地市"){
workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Range(array[1]).EntireRow.Clear();
}
}
var st5LastRow1 =workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Cells(workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Rows.Count, 1).End(xlUp).Row;
for(let y = st5LastRow1; y>0; y--){
if(Application.WorksheetFunction.CountA(workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Rows(y))==0){
workObjects[sheet2Range2ItemValue].Worksheets("Sheet1").Rows(y).Delete();
}
}
//关闭表格
newWork.Close(true);
}
//删除源表格Sheet2页,设置不弹出是否删除的提示框,执行删除完毕后开启
Application.DisplayAlerts = false;
ws2.Delete();
Application.DisplayAlerts = true;
}