Highlight Cells with Italicized Text

56 Views Asked by At

I have created a tab in the menu bar to hold my Schedule function. This is meant to highlight cells with italicized text to a bright yellow. When I run the script below, I get an error reading: Exception: The starting column of the range is too small.

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  var menu = ui.createMenu("Scheduling");
  menu.addItem("Schedule","schedule");
  menu.addToUi();
}

function schedule() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CANVAS");
  var col = ss.getLastColumn();
  var row = ss.getLastRow();
  for (var i = 1; i <= col; i++) {
    for (var j = 1; j <= row; i++) {
      if (ss.getRange(i,j).getFontStyle() == "italic") {
        ss.getRange(i,j).setBackground("#fff2cc");
        j = j+1;
      } else {
        j = j+1;
      }
      i = i+1;
      j = 0;
    }
  }
}
2

There are 2 best solutions below

0
Cooper On

Try it this way:

function schedule() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CANVAS");
  var col = ss.getLastColumn();
  var row = ss.getLastRow();
  //reversed row and col end points from your code
  for (var i = 1; i <= row; i++) {
    for (var j = 1; j <= col; i++) {
      if (ss.getRange(i,j).getFontStyle() == "italic") {
        ss.getRange(i,j).setBackground("#fff2cc");
        j = j+1;
      } else {
        j = j+1;
      }
      i = i+1;
      j = 0;
    }
  }
}
0
Aerials On

You have a few mistakes in the way you are building your loop. Have a look at the comments I the following code:

function schedule() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CANVAS");
  var col = ss.getLastColumn();
  var row = ss.getLastRow();
  // For each column
  for (var i = 1; i <= col; i++) {
    // Loop through the rows
    for (var j = 1; j <= row; j++) {  // Error! i++ should be j++.
      // Check font-style
      if (ss.getRange(i,j).getFontStyle() == "italic") {
        // If italic, color the background
        ss.getRange(i,j).setBackground("#fff2cc"); 
        /* The following makes no sense here... If all you are verifying 
is the italic condition, then let the loop finish and j will be incremented */
        // j = j+1;
      } 
    }
  }
}