根据背景颜色获取值的总和 - Google Sheets

Cli*_*amp 1 javascript google-sheets google-apps-script google-sheets-formula

可以在谷歌表中根据格式对一行数据求和,例如:

sumif(a1:d1, if background is green)
Run Code Online (Sandbox Code Playgroud)

soM*_*rio 5

解释:

我认为实现您的目标的唯一方法是使用Google Apps 脚本,尤其是自定义函数

以下自定义函数totalColor(cells,color)接受您要检查单元格单元格范围以及您选择的颜色

以下是所有可用颜色的列表:

红莓、红色、橙色、黄色、绿色、青色、矢车菊蓝色、蓝色、紫色、洋红色、灰色、白色、黑色

该函数返回的量,所述细胞的值的和背景颜色是一个选择的颜色


解决方案:

function totalColor(cells,color) {
    
const jsonColor = {
    redberry: [ '#980000','#e6b8af','#dd7e6b','#cc4125','#a61c00','#85200c','#5b0f00'],
    red: [ '#ff0000','#f4cccc', '#ea9999','#e06666','#cc0000','#990000','#660000' ],
    orange:[ '#ff9900','#fce5cd','#f9cb9c','#f6b26b','#e69138','#b45f06','#783f04' ],
    yellow: [ '#ffff00','#fff2cc','#ffe599','#ffd966','#f1c232','#bf9000','#7f6000' ],
    green: [ '#00ff00','#d9ead3','#b6d7a8','#93c47d','#6aa84f','#38761d','#274e13' ],
    cyan:  [ '#00ffff','#d0e0e3','#a2c4c9','#76a5af','#45818e','#134f5c','#0c343d' ],
    cornflowerblue: [ '#4a86e8','#c9daf8','#a4c2f4','#6d9eeb','#3c78d8','#1155cc','#1c4587' ],
    blue:[ '#0000ff','#cfe2f3','#9fc5e8','#6fa8dc','#3d85c6','#0b5394','#073763' ],
    purple: [ '#9900ff','#d9d2e9','#b4a7d6','#8e7cc3','#674ea7','#351c75','#20124d' ],
    magenta: [ '#ff00ff','#ead1dc','#d5a6bd','#c27ba0','#a64d79','#741b47','#4c1130' ],
    grey:["#666666", "#999999", "#b7b7b7", "#cccccc", "#d9d9d9", "#efefef", "#f3f3f3"],
    white: ["#ffffff"],
    black: ["#000000"]
  };  
  
const colorArr = jsonColor[color]; 
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const range = sheet.getRange(cells);
const hex_array = range.getBackgrounds().flat();
const values = range.getValues().flat();
var total = 0; 
hex_array.forEach((h,i)=>{                    
  if(colorArr.includes(h)){
  total += values[i];
  }                    
}); 
return total;  
}
Run Code Online (Sandbox Code Playgroud)

然后通过使用 定义单元格或单元格范围和颜色"",将其用作工作表中的简单公式,例如:

=totalGreens("A1:D1", "green")
Run Code Online (Sandbox Code Playgroud)

例子


如何创建自定义函数的说明:

  1. 单击工具=>脚本编辑器

设置

  1. 上述代码片段复制并粘贴到脚本编辑器中,然后单击保存按钮:

例子2