首页 > 解决方案 > 使用斜体文本突出显示单元格

问题描述

我在菜单栏中创建了一个选项卡来保存我的计划功能。这意味着将带有斜体文本的单元格突出显示为亮黄色。当我运行下面的脚本时,我收到一条错误消息: 异常:范围的起始列太小。

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;
    }
  }
}

标签: google-apps-scriptgoogle-sheetsgoogle-sheets-apigoogle-apps-script-editor

解决方案


您在构建循环的方式上存在一些错误。看看我下面代码的评论:

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;
      } 
    }
  }
}

推荐阅读