【问题标题】:Google sheets scrip conditional formatting error: The number of rows in the data does not match the number of rows in the range谷歌表格脚本条件格式错误:数据中的行数与范围内的行数不匹配
【发布时间】:2020-11-12 17:02:25
【问题描述】:

我正在尝试编写格式化脚本。我被一些条件格式困住了。我需要让列根据单元格中的值更改颜色。我的代码如下。我收到以下错误:

异常:数据中的行数与 范围内的行。数据有 920,但范围有 999。(第 52 行, 文件“代码”)

  //Conditional Formatting for transaction status column
  var rangeA = sheet.getRange("L2:L");
  var valuesA = rangeA.getValues();
  var backgrounds = [];
  var textColorTransaction = [];
  
  for(var i = 0; i < valuesA.length; i++) { //for each row that the data is present
    var aValue = valuesA[i][0];
    if(aValue == "Declined"){ //if value = Declied
      backgrounds.push(["#F39581"]);
    } else if(aValue == "Credit"){
      backgrounds.push(["#FCE8B2"])
      textColorTransaction.push(["red"]);
    } else {
      backgrounds.push([null]); //using null will reset the background color formatting
      textColorTransaction.push([null])
      }
  }
  rangeA.setBackgrounds(backgrounds); //Set the background colors all at once for speed.
  rangeA.setFontColors(textColorTransaction);

【问题讨论】:

标签: google-apps-script google-sheets


【解决方案1】:

解释/问题:

  • if 语句的第一个块评估为真时,您忘记添加一行以将元素推送到textColorTransaction。因此,在 for 循环结束后,textColorTransaction 的大小小于您的范围 rangeA

  • 这是因为for 循环迭代直到列的长度,但是当单元格值等于"Declined" 时,您不会将任何元素推送到textColorTransaction。结果,textColorTransaction 最终小于 valuesA 的长度。

  • 获取完整列 L 可能是您的目标,但您可能需要考虑到包含内容的最后一行。您可以将sheet.getRange("L2:L"); 替换为sheet.getRange("L2:L"+sheet.getLastRow());。这是一个可选步骤,因此不包含在我的解决方案中。

解决办法:

  var rangeA = sheet.getRange("L2:L");
  var valuesA = rangeA.getValues();
  var backgrounds = [];
  var textColorTransaction = [];
  
  
  for(var i = 0; i < valuesA.length; i++) { //for each row that the data is present
    var aValue = valuesA[i][0];
    if(aValue == "Declined"){ //if value = Declied
      backgrounds.push(["#F39581"]);
      textColorTransaction.push(["yellow"]); // <- NEW CODE ADDED
    } else if(aValue == "Credit"){
      backgrounds.push(["#FCE8B2"])
      textColorTransaction.push(["red"]);
    } else {
      backgrounds.push([null]); //using null will reset the background color formatting
      textColorTransaction.push([null])
      }
  }
  rangeA.setBackgrounds(backgrounds); //Set the background colors all at once for speed.
  rangeA.setFontColors(textColorTransaction);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2022-07-15
    • 2016-10-01
    相关资源
    最近更新 更多