首页 > 解决方案 > 从一个单元格值到现有单元格值的递归加法函数

问题描述

我正在使用谷歌表格。我有一个这样的工作表:

(对不起,我不知道如何在这里链接图片。我只用文字做的表格变得锯齿状)

当用户将 A1 的值从 100 更改为 150 时,我希望 B1 的值从 200 更改为 350。下次用户将 A1 的值从 150 更改为 200 时,我希望 B1 的值从 350 更改为 550 ......等等。

可悲的是,我是编程新手。所以,我正在学习如何在 Google 表格中使用脚本。

问题

标签: google-apps-scriptgoogle-sheetscumulative-sum

解决方案


一种可能的解决方案,假设第一行中的所有值都会触发其余值的更新。

已编辑:调整为仅考虑 A1 中的更改,并始终将 A1 的新值添加到第一行的其他单元格中;还强制脚本解释数字以避免一些不希望的连接。

function onEdit(e){
  if (e.range.getA1Notation() == "A1") { 
    var difference = isNaN(e.value) ? 0 : Number(e.value); // New value of A1 to be added to the other cells in first row ; only taking numbers into account
    var firstRowValues = e.range.getSheet().getRange("1:1").getValues(); // Get the current values of the first row
    for (var c = 1 ; c < e.range.getSheet().getLastColumn() ; c++){
      // Go through each value in first row
      // If it has a value already, and if that value is a number, add the difference
      if (firstRowValues[0][c] && !isNaN(firstRowValues[0][c])) firstRowValues[0][c] = Number(firstRowValues[0][c]) + difference;
    }
    e.range.getSheet().getRange("1:1").setValues(firstRowValues); // Set the updated value in the sheet's first row

  }
}

编辑:在原始问题中添加屏幕截图后,我知道只有 B1 需要更新,因此代码可以简化如下:

function onEdit(e){
  if (e.range.getA1Notation() == "A1") { 
    var difference = isNaN(e.value) ? 0 : Number(e.value); // New value of A1 to be added to the other cells in first row ; only taking numbers into account
    var valueB1 = e.range.getSheet().getRange("B1").getValue(); // Get the current values of B1
    if (valueB1 && !isNaN(valueB1)) valueB1 = Number(valueB1) + difference; // Only updating if B1 has a value which is a number
    e.range.getSheet().getRange("B1").setValue(valueB1); // Set the updated value in B1  
  }
}

推荐阅读