google-sheetsgoogle-apps-script

Google Sheet run a formula that was written on a different sheet


I have an issue where I want to automate this process where some calculation is performed.

Link for the image: https://i.sstatic.net/9dxXRqKN.png

Column F Column G Column H
Formula Price Formula * Price
SUMIF('Sheet1'!A:A;'Sheet2'!$A$1;Sheet1'!B:B) 10 =F2*G2
COUNT('Sheet1'!A:A) 5 =F3*G3
COUNTIF('Sheet1'!B:B,'Sheet2'!$B$1) 3 =F4*G4

As a description of the table, I did an import range that would bring Column F which contains the formula and Column G which contains the price, I would like to automate it so that Column H would be the multiple of Column F and Column G. It so happens that Column F and Column G is taken from different sources.

Any attempt to trick it into thinking that it is a formula for example like =("="&F2)*G2 would lead to it saying:

"Function MULTIPLY parameter 1 expects number values. But Function MULTIPLY parameter 1 expects number values. But '=SUMIF('Sheet1'!A:A;'Sheet2'!$A$1;Sheet1'!B:B)' is a text and cannot be coerced to a number.

I've tried this but it doesn't seemed to work:

const sheet = SpreadsheetApp.getActiveSheet();
let formula = sheet.getRange(1, 5, sheet.getMaxRows(), 1).copyTo(sheet.getRange(1, 8));
target = sheet.getRange(1,8);
sheet.getRange(1,8).setFormula('='+ target);

Any help would be highly appreciated, thank you.


Solution

  • Use Array.map() and Range.setFormulas(), like this:

    function setFormulas() {
      const sheet = SpreadsheetApp.getActiveSheet();
      const formulas = sheet.getRange(1, 5, sheet.getLastRow(), 1)
        .getDisplayValues()
        .map(row => row.map(s => s ? '=' + s : null));
      sheet.getRange(1, 8, formulas.length, formulas[0].length).setFormulas(formulas);
    }
    

    See Array.map() and Range.setFormulas().

    Alternatively, use an array formula with logic to decide which calculation to do in each row, avoiding scripting altogether.