简体   繁体   中英

Google Sheets - If statement to populate cell

It feels like this should be really easy, but I keep getting errors related to circular logic.

Column C "Total" will always be entered by the user first. If user enters number in Column B "Variable" then Column A "Fixed" will be populated with C - B. If user enters number in Column A "Fixed", then Column B "Variable" will be populated with C - A.

https://docs.google.com/spreadsheets/d/1xBbU6A_MDK6fyLjdFUD7X06b7BQ1VhQ-FWQBET4cLso/edit?usp=sharing

You are trying to add formulas that will always need to rely on eachother to produce an output and as result of that, it will run into a Circualr Dependency error.

Possible solution:

Try using the "Iterative Calculation" option under File –> Spreadsheet Settings –> Calculation. You can see the description for Iterative Calculation here .

Here is one way to avoid circular references: do not hand enter any formulas, but use an onEdit() script to insert formulas programmatically only when necessary.

The following script will enter a formula in column B when column A is edited, and vice versa:

function onEdit(e) {
  if (!e) {
    throw new Error('Please do not run the script in the script editor window. It runs automatically when you hand edit the spreadsheet.');
  }
  const watchSheet = /^(Sheet1|Sheet2|Sheet3|Sheet4)$/i;
  const watchColumns = [
    {
      colNumber: 1,
      formula: '=C:C - B:B',
    },
    {
      colNumber: 2,
      formula: '=C:C - A:A',
    },
  ];
  const sheet = e.range.getSheet();
  if (!sheet.getName().match(watchSheet)) {
    return;
  }
  const editedColumn = watchColumns.filter(column => column.colNumber === e.range.columnStart)[0];
  if (!editedColumn) {
    return;
  }
  const updateColumns = watchColumns.filter(column => column.colNumber !== editedColumn.colNumber);
  updateColumns.forEach(column => {
    sheet
      .getRange(e.range.rowStart, column.colNumber)
      .setFormula(column.formula);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM