Tuesday, September 4, 2012

How to conditionally change the color of the entire row

Note:

I have updated the script so that you can easily change the range, so now it can work to check duplicates in any column or any row or any range. And it is much more optimized:



Question:

What I need to do is compare the first cell in every row with the previous row's first cell. (The first cells are dates.) If the month has changed I want the row to turn a color that way it will be easy to tell when a month has changed.






Solution:

Here is the script that will look into the duplicate values in Column A, and it will color these duplicate cells to "YELLOW" color (you can change this color to whatever you want).

Note:
Before running this function (script) you have to first change the color of whole Column A to white color or any other color, so that if you have already "YELLOW" color to some cell and if it is not a duplicate then this script is not going to change to white color, so you have to take care of it.

And this script will take a little bit of your time to execute, so you have to be patient.

Here is the script:


//===================================


function onOpen() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var menuEntries = [ {name: "Check Dates", functionName: "CheckDates"}];
 ss.addMenu("Scripts", menuEntries);
};

function CheckDates() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1"); //change it to whatever your sheet name is

  var datarange = sheet.getDataRange();
  var rows = datarange.getLastRow();


  for(i=1;i<rows;i++)
  {
    var var1 = datarange.offset(i-1, 0, 1, 1).getValue();
    var var2 = datarange.offset(i, 0, 1, 1).getValue();
 
    if ( var1 != "" && var2 != "" )
    {
      try
      {
        if( var1.getMonth() != var2.getMonth() )
        {
          // it will color entire row upto column no. 5
          datarange.offset(i, 0, 1, 5).setBackground("YELLOW");
        };
      }
      catch(e)
      {
     
      }
   
    };
  };

}



//=================================


If you are new to Google Spreadsheet Scripts, then please have a look at the following link:


I hope this script will help you, and if you need more help then please do comment below on this blog itself.

If this blog post was helpful to you, and if you think you want to help me and make my this blog survive then please `donate here: http://igoogledrive.blogspot.com/2012/09/donate.html 

Thanks,
Kishan,

3 comments:

  1. Hello Kishan,
    How can I modify this script to compare the values of two columns in the same row and if it is a match then change the entire row's background color?

    Thanks in advance.
    Wilson

    ReplyDelete
  2. Is that working for date condition can anyone please update the script for text

    ReplyDelete
  3. this is enough to make me miss excel!

    ReplyDelete