Saturday, September 22, 2012

Counting Unique Colors in a Range in Google Spreadsheet

Counting Unique Colors in a Range in Google Spreadsheet


Following is the script for Counting Unique Colors in a Range:


function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [ {name: "CountColors", functionName: "CountUniqueColors"}];
  ss.addMenu("CountColors", menuEntries);
}

function CountUniqueColors() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName("Sheet1"); //Change sheet name as per your requirement

  var colorRange = s.getRange("A1:A100"); //You can change this range as per your requirement
  var BackGroundColors = colorRange.getBackgroundColors();

  var counter = 0;

  var ColorArray  = new Array();
  ColorArray.push(BackGroundColors[0][0]);


  for(var row = 0; row < BackGroundColors.length; row++ )
  {
    for(var col = 0; col < BackGroundColors[0].length; col++ )
    {
      var colorFound = false;
   
      for (var j in ColorArray)
      {
        if( ColorArray[j] == BackGroundColors[row][col] )
        {
          colorFound = true;
        }
      }
   
      if(colorFound == false)
      {
        ColorArray.push(BackGroundColors[row][col]);
        counter++;
      }
    }
  }

  Browser.msgBox(counter);
}


I have used message box to display the result, which can be changed according to your requirement.

And If you are not much familiar with scripts then check out the following link:
http://igoogledrive.blogspot.in/2012/08/how-to-write-script-in-google.html

I hope the above solution will help you, and if you need more help then please do comment below on this blog itself, I will try to help you out.

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

Thanks,
Kishan,

No comments:

Post a Comment