目录
系列文章
后续常见问题、颜色附录,持续更新中...
5、Excel实战
使用for循环给10*10的表格填充行列之和
---------------------------------------------分割---------------------------------------------
使用for循环将10*10表格中的偶数值提取到另一个sheet页
---------------------------------------------分割---------------------------------------------
使用for循环给写一个99乘法表
11 = 1
1 2 = 2 22 = 4
1 3 = 3 23 = 6 3 3 = 9
...
---------------------------------------------分割---------------------------------------------
按市场成员名称分类(即市场成员A、B、C...),统计月内不同时间段表1和表2的乘积之和(月内所有天数00:15~24:00时间段的乘积和)。
javascript
function 获取每月市场成员数据乘积和(){
let activeWorkbook = Application.ActiveWorkbook;
if(activeWorkbook.Name !== '市场成员数据.xlsx'){
console.log('文件选择错误 ')
return
}
// 基本数据表
let sheet1 = Sheets.Item("sheet1");
let sheet2 = Sheets.Item("sheet2");
// 将基本数据表转换为以下格式
/*
let mx = {
'市场成员A': {
cost:0, // 乘积和
days:[{
day: 1,
cost: 0, // 单日乘积和
times: [{
time: '00:15',
cost: 0, // sheet1数据 * sheet2数据
},{
time: '00:30',
cost: 0, // sheet1数据 * sheet2数据
},...]
},{
day: 2,
cost: 0,
times: [...]
},...]
}
}
*/
// 定义存放月全部市场成员数据对象
let mx = {};
// 循环sheet1表。i行j列。sheet1页起始行为2,结束行为4173
for(let i = 2; i < 4174; i++){
// 获取市场成员名称
let name = sheet1.Cells(i, 1).Value2;
// 获取日期
let date = sheet1.Cells(i, 4).Text;
// 从日期yyyy/mm/dd中获取dd,*1可以将字符串转换为数字。下面的代码中需要用day做+法,所以要转换为数字。
let day = date.split('/')[2] * 1;
// 定义每天的乘积和
let dayCost = 0;
// 定义存放96时段数据数组
let dayTimes = [];
// 共96列+起始列7 = 103
for(let j = 7; j < 103; j++){
// sheet1数据
let sheet1Data = sheet1.Cells(i, j).Value2 || 0
// sheet2数据
// j=7时00:15,sheet2表为第2列;j=8时00:30,sheet2表为第3列,所以j-5为sheet2的行。
// day为日,所以+1为sheet2的列。
let sheet2Data = sheet2.Cells(j - 5, day + 1).Value2 || 0
// 分时乘积
let cost = sheet1Data * sheet2Data
// 存放每个分时的sheet1数据
dayTimes.push({
time: sheet1.Cells(1, j).Value2,
cost
})
// 将分时乘积相加获得一天的乘积和
dayCost += cost
}
// 定义存放每天各市场成员的数据对象
let dayData = {
day,
cost: dayCost,
times: dayTimes
}
// 将dayData按市场成员名分组存放,并计算月和
if(!mx[name]){
mx[name] = {
cost: dayData.cost,
days: [dayData]
}
}else{
mx[name].cost += dayData.cost;
mx[name].days.push(dayData);
}
}
// 下面的全部是打印,可以全部注释掉
// console.log(JSON.stringify(mx))
// 获取全部市场成员名数组
let names = Object.keys(mx);
// 循环市场成员数组
let costCount = 0
for(let i = 0; i < names.length; i++){
// 打印每个市场成员的乘积和
let name = names[i];
costCount += mx[name].cost;
console.log(name + ',乘积和为:' + mx[name].cost);
}
console.log('全部市场成员乘积总和:' + costCount)
}