【发布时间】:2017-08-02 20:45:44
【问题描述】:
我正在尝试使用从我的谷歌表格中的其他选项卡收集的特定值填充一个选项卡中的单元格范围。但是,我无法为其编写正确的脚本。
这里有更详细的解释:
我的 google 表格文档中有几个选项卡代表一年中的一个月,即它们被命名为 July 2017、December 2016 等等。此外,我还有另外两个名为 Graphs 和 Blank 的选项卡。
每个月标签在其N6 单元格中都有这样的值:Balance 33050,32 UAH(数字可能因标签而异)。
我想做的事:
我需要从我的所有月份选项卡中收集 N6 值并将这些值填充到 Graphs 选项卡的 A 列中。然后我需要从我收集的所有值中构建一个图表。但目前的主要问题是正确收集值。
我试图为此编写一个脚本,但似乎我做错了什么。我对谷歌脚本的东西很陌生,所以也许我在这里遗漏了一些简单的东西。
这是我的脚本:
var months = [
"january","february","march","april","may","june","july","august","september","october", "november","december"
];
var graphSheetName = 'Graphs';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var graphSheet = ss.getSheetByName(graphSheetName);
// this function tells if the name of the tab refers to one of the month tabs.
function isMonthSheet(name) {
return matchInArray(name, months);
}
function matchInArray(string, expressions) {
var len = expressions.length,
i = 0;
for (; i < len; i++) {
if (string.toLowerCase().match(expressions[i])) {
return true;
}
}
return false;
}
// This function runs on every edit of the google sheets document.
// It should fill the cells in the `Graphs` tab.
function getMonthsTotals() {
var sheets = ss.getSheets(); // get all tabs
var values = [];
for (var i = 0; i < sheets.length; ++i) {
var sheet = sheets[i];
// if it is a month tab, collect the N6 value into the `values` array.
// "Balance 33050,32 UAH".slice(8,-4) --> "33050,32".
if (isMonthSheet(sheet.getName())) {
var value = sheet.getRange('N6').getValue().slice(8, -4);
values.push(value);
}
}
// fill the `Graphs` tab with the collected values into the `A` column.
var rangeStr = 'A1:A' + values.length;
graphSheet.getRange(rangeStr).setValues(values);
}
正如我上面已经说过的,我对 google sheet 脚本很陌生,所以我对调试也不是很熟悉,所以我的方法是使用 toast 函数。因此,我无法提供关于脚本实际运行方式的太多信息。
我就如何更正我的脚本以使其正确运行寻求建议和帮助。
【问题讨论】:
-
"我好像做错了什么。"无助于诊断问题。结果与预期有何不同?
标签: google-apps-script google-sheets google-docs google-spreadsheet-api google-sheets-api