如何在 Google 表格中编写自定义公式/脚本

问题描述 投票:0回答:1

我想在 Google 表格中编写一个函数或脚本,允许我在一列 (A) 中输入一个值,按下 Enter 键后,将从一列 (B) 中减去该值并添加到另一列 ( C)? B 列和 C 列都只包含值,没有公式。我还希望按 Enter 键后重置值 (A)。

即。 B 列= 10 C 列= 10 --> 输入“5”后,在 A 列中“Enter” --> B 应更改为 5,C 应更改为 15,A 重置为空字段

我找到了一个宏,可以在Excel中执行此操作,但无法将其转换为Google Sheets,并且它只执行了一半的功能(仅从一列中减去,没有添加到第三列)。

google-sheets google-apps-script google-sheets-formula
1个回答
0
投票

您可以使用 onEdit 函数来完成此操作。每次编辑工作表时,此功能都会自动运行。在代码中,检查编辑的值是否为A列,然后执行B和C的计算并重置A。

以下功能将根据您的要求执行操作。

function onEdit(e) {
  var sheet = e.source.getActiveSheet();
  var range = e.range;
  var col = range.getColumn();
  var row = range.getRow();
  
  // Check if the edited cell is in column A and not in the header row
  if (col == 1 && row > 1) {
    var value = range.getValue();
    
    // Get the current values in columns B and C
    var bValue = sheet.getRange(row, 2).getValue();
    var cValue = sheet.getRange(row, 3).getValue();
    
    // Subtract the entered value from column B and add it to column C
    sheet.getRange(row, 2).setValue(bValue - value);
    sheet.getRange(row, 3).setValue(cValue + value);
    
    // Clear the input cell in column A
    range.clearContent();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.