Home > Back-end >  Google Spreadsheets Add old number with new number
Google Spreadsheets Add old number with new number

Time:12-24

I am trying to add a number to an old number. For example A1 contains "5", and I write "10" into B1, then A1 should show "15".

When I type "10" in B1 again, then A1 should show "25", so A1 adds the previous number with the new number.

I dont want to do mental arithemtic every time. Is this possible with Google Sheets?

CodePudding user response:

I thought that in your situation when Google Apps Script is used, your goal might be able to be achieved. The sample script is as follows.

Sample script:

Please copy and paste the following script to the script editor of Google Spreadsheet, and save the script.

function onEdit(e) {
  const range = e.range;
  if (range.getA1Notation() != "B1") return;
  const [a, b] = range.offset(0, -1, 1, 2).getValues()[0];
  range.offset(0, -1).setValue(a   b);
}

Testing:

When you use this script, please put a number to the cell "B1". By this, the script is automatically run by firing the OnEdit trigger as follows. So when you directly run the script with the script editor, an error occurs because the event object is not declared. Please be careful this.

enter image description here

Note:

  • This is a simple sample script from your question. So when your actual situation is different from your question, please modify the above script.

Reference:

  • Related