Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-formula

How To Convert A Range of Strings To Formulas


In column B I have some area descriptions (e.g.,63.5x88) and in column C I want to calculate the areas (e.g., 5588).

With reading previous answers I have the below script, but the problem is it only calculates B2 and enters that answer for all of C2:C. How do I have it evaluate each description and put the corresponding result in the area column? Thank you!

function setFormula(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var source= sheet.getRange('B2:B');
  var formula = source.getValue();
  formula = formula.replace('x', '*'); 
  var target = sheet.getRange('C2:C');
  target.setFormula(formula);
}

I imagine all I might need is a simple loop, but I'm new to scripts.

If there's a way to do this with a simple formula rather than a script, that would be even better.


Solution

  • If there's a way to do this with a simple formula rather than a script, that would be even better.

    Yes, that can be done with a plain vanilla spreadsheet formula:

    =product(split(B2, "x"))
    

    Put the formula in cell C2. To apply it to the whole column B2:B, use map(), like this:

    =map(B2:B, lambda(t, 
      if(len(t), product(split(t, "x")), t) 
    ))
    

    See map() and split().