【发布时间】:2021-12-08 20:46:19
【问题描述】:
我在 Google 电子表格中有一个主表,如下所示;
我想要的是从谷歌电子表格中的给定标签/工作表(A 列)中获取颜色计数。根据我对 stackoverflow 的研究,我发现在活动单张纸上运行完美的代码 (https://stackoverflow.com/a/57571668/12906920);
function countColoredCells(countRange,colorRef) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formula = activeRange.getFormula();
var backgrounds = activeSheet.getRange(countRange).getBackgrounds();
var colorRefBackground = activeSheet.getRange(colorRef).getBackground();
var count = 0;
for(var i=0;i<backgrounds.length;i++)
for(var j=0;j<backgrounds[0].length;j++)
if( backgrounds[i][j] == colorRefBackground )
count=count+1;
return count;
};
但我无法添加工作表名称(单元格值)作为参数。例如;要参考 B1 在给定范围内获得给定的 sheet2 颜色,我的函数可能是:
countColoredCells(countRange,colorRef,sheet_name) > countColoredCells(F1:F30,B1,A2)
该函数查看将搜索哪些工作表的范围,并从主 excel 中的参考颜色返回计数值。有人可以帮我怎么做吗?
更新
这里是修改后的代码,但我仍然得到“范围未找到错误”
function countColoredCells(countRange,colorRef,sheetName) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(sheetName));
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formula = activeRange.getFormula();
var backgrounds = activeSheet.getRange(countRange).getBackgrounds();
var colorRefBackground = activeSheet.getRange(colorRef).getBackground();
var count = 0;
for(var i=0;i<backgrounds.length;i++)
for(var j=0;j<backgrounds[0].length;j++)
if( backgrounds[i][j] == colorRefBackground )
count=count+1;
return count;
}
【问题讨论】:
-
您是否尝试过修改函数以添加工作表名称参数和
.getSheetByName()方法? -
恕我直言,如果您展示您尝试使代码适应您的特定需求,您将有更多机会获得帮助。
-
@cybernetic.nomad 我认为 Google Sheets 不支持 VBA。Sheets 支持 Javascript 函数就像宏一样工作
-
@TheMaster .getSheetByName 很好,但我有超过 30 个选项卡/工作表,每次我需要手动添加字符串。它需要参数作为字符串,但我无法将选定的单元格作为字符串参数传递给该工作表名称。
-
你可以通过。看看
countRange是如何通过的。有关 JavaScript 基础知识的免费资源,请参阅 tag info page。完成一个完整的课程只需要 5 个小时,而 5-15 分钟就能得到你想要的东西。如果你仍然没有得到它,edit 你的问题与你的尝试。
标签: google-apps-script google-sheets google-sheets-formula google-sheets-api