Search code examples
javascriptif-statementgoogle-apps-scriptgoogle-sheetscomparison-operators

How do I find the cell with a certain background color, and set background of different cell in relation to it?


I am trying to make a code that finds the red cell on the spreadsheets, and moves it up one cell. Here is what I have:

var ymax = 23;
var xmax = 23;
var playerx = 0;
var playery = 0;
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
function moveup(){
findplayer();
sheet.getRange(playerx, playery + 1).setBackground('red');
sheet.getRange(playerx, playery).setBackground('white');
}
function findplayer(){
for(var x = 1; x < xmax; x++)
  for(var y = 1; y < ymax; y++)
  {
    var cell = sheet.getRange( 'a1:z23' ).getCell(x, y).getBackground();
    if(cell = 'red'){
      var playerfound = true;
      playerx = x;
      playery = y;

    }
  }
if (playerfound = false)
{
  findplayer();
  }
 }
 function onOpen() {
 var ui = SpreadsheetApp.getUi();
 ui.createMenu('controol')
   .addItem('up', 'moveup')
   .addToUi();
 }

For some reason instead of moving the red square from T10, it just makes a new one at W22.

What am I doing wrong?

also I claim rights


Solution

  • The following comparisons has an error:

    cell = 'red'
    

    playerfound = false
    

    They use a single equality sign wich in JavaScript is used to assign a value to a variable, instead it should use == (abstract equality) or === (strict equality).

    By the other hand, getBackground() returns the color code, not the color name, so instead of red use #ff0000.