Script to return a value on a specific cell if oth

2019-08-12 14:30发布

问题:

I'm just getting started with Google scripts and I'm trying to create a very basic script to help me understand the fundamentals.

The script would look for the number 5 in cell E2 and then return a value of 5 if true or 10 if false. The issue I'm running into is that if I enter a 5 on E2 I do not get a 5 on E4. it always says 10 on E4.

I have tried changing the operator to = and === as well as putting quotes ("5") around the 5 to look for text rather than a number and can't get it to work.

function onEdit()
{

var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var cell = sheet.getRange(2,5);
var cell2 = sheet.getRange(4,5);


  if (cell == 5) {cell2.setValue(5);}
  else {cell2.setValue(10);}


}

回答1:

The mistake is in comparison cell == 5. It should be cell.getValue() == 5.

Indeed, cell is an object that abstractly represents the cell: by calling one its methods, you can change its value, or make the background red, or set data validation, etc. getValue is one of these methods, which returns the value contained in the cell.