Christopher Barnes
Christopher Barnes

Reputation: 11

Looping conditional formatting.

I want this code to loop through all columns in the sheet. I am a teacher and would like to use this code to grade spreadsheets but right now the code only works for column G. Any help would be appreciated.

function conditional() {
    var sheet = SpreadsheetApp.getActiveSheet();
    var numRows = sheet.getLastRow()+1;
    var numC = sheet.getLastColumn(); 

for (var t = 7; t = numC; t++){
    var range = sheet.getRange(2,t,numRows,1);
    var answer = sheet.getRange(2,t).getValue();
    var rule = SpreadsheetApp.newConditionalFormatRule()
   .whenTextEqualTo(answer)
   .setBackground("#00ff00")
   .setFontColor("#00ff00")
   .setRanges([range])
   .build();
   var rules = sheet.getConditionalFormatRules();
   rules.push(rule);
   sheet.setConditionalFormatRules(rules);

   var rule2 = SpreadsheetApp.newConditionalFormatRule()
  .whenTextDoesNotContain(answer)
  .setBackground("#ff0000")
  .setFontColor("#ff0000")
  .setRanges([range])
  .build();
   var rules2 = sheet.getConditionalFormatRules();
   rules2.push(rule2);
   sheet.setConditionalFormatRules(rules2);
   }
   }

Upvotes: 0

Views: 220

Answers (1)

J-J
J-J

Reputation: 5871

The problem is with your for loop, you have to change the for loop as follows.

for (var t = 1; t <= numC; t++)

Here what I did is, I have modified the for loop syntax to iterate from column A till the last columns.

Upvotes: 1

Related Questions