正在为我的函数sumBlack()寻找更好的传递范围的方法



我很想在谷歌表单中使用我的脚本,只需=sumBlack(C4:14(

目前我的脚本**见下文**在谷歌表单中使用=sumBlack(3,4,14(3代表列,4和14代表行起始和结束

这是我的密码。。。很高兴它能起作用它只对fontColor为黑色的单元格求和


function sumBlack(column, rowst, rowend) {
result = 0;
for(row = rowst;row <= rowend;row++){
var txtColor = SpreadsheetApp.getActive().getDataRange().getCell(row, column).getFontColor();
if(txtColor == "#000000"){
result = result + SpreadsheetApp.getActive().getDataRange().getCell(row, column).getValue();
}
}
return result;
}

我相信你的目标如下。

  • 当字体颜色为#000000为十六进制时,您希望对单元格的值求和
  • 您希望使用自定义函数来实现这一点

修改点:

  • 在这种情况下,为了给自定义函数提供a1Notation,使用=sumBlack("C4:14")而不是=sumBlack(C4:14)怎么样?因为当使用=sumBlack(C4:14)时;C4:14";被给出为二维阵列。这样,就无法知道范围
  • 在该修改中,getFontColors()getValues() are used instead of分别获得FontColor((and获得Value((。通过这种方式,我认为工艺成本将能够降低

当你可以允许这个建议时,下面修改的脚本怎么样?

修改的脚本:

使用此脚本时,请将=sumBlack("C4:14")放到单元格中。在这种情况下,请不要忘记附上带有"的a1符号。

function sumBlack(a1Notation) {
const range = SpreadsheetApp.getActiveSheet().getRange(a1Notation);
const fontColors = range.getFontColors();
const values = range.getValues();
const result = fontColors.reduce((n, r, i) => {
r.forEach((c, j) => {
if (c == "#000000") n += Number(values[i][j]);
});
return n;
}, 0);
return result;
}
  • 如果您想给图纸命名为=sumBlack("Sheet1!C4:14"),请按如下方式修改上面的脚本。

    • 来自

      const range = SpreadsheetApp.getActiveSheet().getRange(a1Notation);
      
    • const range = SpreadsheetApp.getActiveSpreadsheet().getRange(a1Notation);
      
  • 在上述修改后的脚本中,当=sumBlack("C4:14")被放入并且单元值"0"为0时;C4:14";更改,则不进行重新计算。如果要针对这种情况重新计算,请添加以下脚本。编辑活动工作表中的单元格时,将自动运行以下脚本,并重新计算=sumBlack()的公式。

    function onEdit(e) {
    const sheet = e.source.getActiveSheet();
    sheet.createTextFinder("=sumBlack").matchFormulaText(true).replaceAllWith("###sumBlack");
    sheet.createTextFinder("###sumBlack").matchFormulaText(true).replaceAllWith("=sumBlack");
    }
    

参考文献:

  • getFontColors((
  • 获取值((
  • reduce((
  • 类TextFinder

最新更新