Office Script需求:将空行统计脚本改为统计S列空单元格
统计Excel工作表S列空单元格数量的Office Script解决方案
现有一段用于统计工作表空行的Office Script代码,需要修改为统计固定S列的空单元格数量,原代码如下:
function main(workbook: ExcelScript.Workbook): number { // Get the worksheet named "Sheet1". const sheet = workbook.getWorksheet('Data'); // Get the entire data range. const range = sheet.getUsedRange(true); // If the used range is empty, end the script. if (!range) { console.log(`No data on this sheet.`); return; } // Log the address of the used range. console.log(`Used range for the worksheet: ${range.getAddress()}`); // Look through the values in the range for blank rows. const values = range.getValues(); let emptyRows = 0; for (let row of values) { let emptyRow = true; // Look at every cell in the row for one with a value. for (let cell of row) { if (cell.toString().length > 0) { emptyRow = false } } // If no cell had a value, the row is empty. if (emptyRow) { emptyRows++; } } // Log the number of empty rows. console.log(`Total empty rows: ${emptyRows}`); // Return the number of empty rows for use in a Power Automate flow. return emptyRows; }
修改后的代码
function main(workbook: ExcelScript.Workbook): number { // 获取名为"Data"的工作表 const sheet = workbook.getWorksheet('Data'); if (!sheet) { console.log("找不到名为'Data'的工作表"); return 0; } // 获取S列的已使用范围(仅包含有数据或曾编辑过的单元格) const columnSRange = sheet.getRange("S:S").getUsedRange(true); if (!columnSRange) { console.log("S列无任何数据"); return 0; } console.log(`S列的已使用范围:${columnSRange.getAddress()}`); // 获取S列的所有单元格值 const columnValues = columnSRange.getValues(); let emptyCellCount = 0; // 遍历S列的每个单元格,判断是否为空 for (let row of columnValues) { const cellValue = row[0]; // 判断单元格是否为空:包括值为null、undefined,或字符串长度为0的情况 if (cellValue === null || cellValue === undefined || (typeof cellValue === 'string' && cellValue.trim().length === 0)) { emptyCellCount++; } } console.log(`S列空单元格总数:${emptyCellCount}`); // 返回空单元格数量,可用于Power Automate流程 return emptyCellCount; }
关键改动说明
- 精准定位S列:直接通过
getRange("S:S")获取整列,再调用getUsedRange(true)筛选出实际有数据交互的单元格范围,减少不必要的遍历 - 更准确的空值判断:覆盖了单元格值为
null、undefined以及仅含空格的空字符串场景,避免原代码中toString()可能引发的异常(比如值为null时调用toString会报错) - 增加异常防护:添加了工作表存在性检查,避免因目标工作表不存在导致脚本崩溃
内容的提问来源于stack exchange,提问作者Richard O'Carroll
相关产品推荐
相关产品推荐

