Google Sheets Summing a cell over a changing number of sheets

坚强是说给别人听的谎言 提交于 2020-07-08 02:52:49

问题


I am trying to convert a Spreadsheet from Excel to Google Sheets. Most formulas have worked as expected, with the exception of this formula:

=SUM('J Slater:Job Sheet'!C6)

I am using it to sum a specific cell over a range of sheets this formula allows sheets to be added between the range an also be added to the sum cell without any change to the formula. I can't find a way of replicating this in Google Sheets.


回答1:


You can do this with custom functions in Google sheets:

Script:

/**
 * @returns {Number} Sum of all values from startSheet to endSheet
 * @customfunction
 *
 * @param {String=} startSheet
 * @param {String=} endSheet
 * @param {String=} range
 */
function SUMSHEETS(startSheet = 'Sheet1', endSheet = 'Sheet2', range = 'A2') {
  if ([...arguments].some(arg => typeof arg !== 'string' || arg === ''))
    throw new Error('All arguments must be non-empty strings');
  const [addValue, getOutput] = (() => {
    let output = 0;
    return [
      sh => {
        output += sh.getRange(range).getValue();
      },
      () => output,
    ];
  })();
  let toggle = 0;
  const end = SpreadsheetApp.getActive()
    .getSheets()
    .some(sheet => {
      if (toggle) addValue(sheet);
      switch (sheet.getName()) {
        case startSheet:
          toggle = 1;
          addValue(sheet);
          break;
        case endSheet:
          return true;
      }
    });
  if (!toggle || !end) throw new Error('Sheet(s) not found!');
  return getOutput();
}

Usage:

=SUMSHEETS("J Slater","Job Sheet","C6")


来源:https://stackoverflow.com/questions/60364340/google-sheets-summing-a-cell-over-a-changing-number-of-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!