【问题标题】:Google App Script for spreadsheet用于电子表格的 Google 应用脚本
【发布时间】:2013-01-13 19:56:51
【问题描述】:

我需要根据其他单元格的值为范围单元格添加背景颜色,但是这个范围有不同的值,例如:

1 X 2 1 X X | 2

在检查值为 2 的 las 单元格时,范围单元格必须是独立颜色,即只有单元格 3 必须具有绿色背景色,因为与红色的值相同。

我有这个代码:

function test() {
  var libro = SpreadsheetApp.getActiveSpreadsheet();
  var range_input = libro.getRange("B3:E3");
  var target_cell = libro.getRange("G3");

  if (range_input.getValues()==target_cell.getValue()) 
  {
    range_input.setBackgroundColor('#58FA58');    
  }

  else
  {
    range_input.setBackgroundColor('#FA5858')
  }  
} 

但问题是这不起作用,因为只有当所有值单元格的值与最后一个单元格的值相同时,该行才显示为绿色,这意味着尽管第三个单元格的值正确,但整行都变为红色。

提前致谢。

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    range_input.getValues() 返回一个包含 4 个单元格的值数组的数组,而 target_cell.getValue() 返回 1 个值。

    function test() {
      var libro = SpreadsheetApp.getActiveSpreadsheet();
      var range_input = libro.getRange("B3:E3");
      var target_cell = libro.getRange("G3").getValue();//Save the value
    
      //Gets the values of the range ([0] to retrieve just the first row of values)
      var input_values = range_input.getValues()[0];
      //Gets the backgrounds of the range ([0] to retrieve just the first row of values)
      var backgrounds = range_input.getBackgroundColors()[0];
    
      //Loop through values in the row, checking against the cell.
      for(var i = 0; i < input_values.length; i += 1){
        if(input_values[i] === target_cell) {
          backgrounds[i] = '#58FA58';
        } else {
          backgrounds[i] = '#FA5858';
        }
      }
      //Put the row of backgrounds back in an array to make it 2d and set the backgrounds
      range_input.setBackgroundColors([backgrounds]);
    } 
    

    【讨论】:

    • 非常感谢,我已经对其进行了测试并工作了。我正在学习 javascript,对此我很菜鸟,有时我会陷入精神状态:-P
    • 没问题,这个网站是提问的好地方。
    猜你喜欢
    • 1970-01-01
    • 2018-03-05
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多