在Google脚本中测试背景

在Google脚本中测试背景

本文介绍了在Google脚本中测试背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅需注意:我不太熟悉编码并且对google脚本是全新的.

Just a note: I am not very versed in coding and brand new to google script.

我正在尝试在脚本中测试背景色.具体来说,我将有一个名称数组存储在一个命名范围内,并希望计算设置为绿色的单元格的数量.
到目前为止,我有以下内容,但收到错误消息:TypeError:无法将未定义的属性"0.0"设置为#00ff00"

I am trying test for background color within a script. Specifically, I will have an array of names stored into a named range and want to count how many cells are set to green.
So far I have the following but receive an error: TypeError: Cannot set property "0.0" of undefined to "#00ff00"

function testCount(range) {

  var ranges = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("testrange");
  var names = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("testrange").getValues();

  var NumColumns = ranges.getNumColumns();
  var NumRows = ranges.getNumRows();
  var c = 0;

  for (var i = 0; i<NumColumns; i++){
    for (var j = 0; j<NumRows; j++){
      if (ranges.getBackgrounds()[i][j] ="#00ff00"){
        c++;
      }else{
        c=c;
      }
    }
  }
  return c;

当我为有颜色的单元格尝试以下操作时,我抓住了绿色的值

I grabbed the value for green when I tried the following for a cell that was colored

return ranges.getBackgrounds()[0][1];

推荐答案

看起来您的代码需要一些清洁.我将解释这些修改.

Just looks like your code needs a little cleaning. I'll explain the edits.

function testCount() {

  var ranges = SpreadsheetApp.getActiveSpreadsheet().getRangeByName("testrange");

不需要var names行,因为您似乎没有使用它.

No need to have the var names line because it seems that you don't use it.

  var NumColumns = ranges.getNumColumns();
  var NumRows = ranges.getNumRows();

一次获取所有单元格的背景并将其存储在变量中.

Grab the backgrounds of all the cells at once and store that in a variable.

  var backgrounds = ranges.getBackgrounds();
  var c = 0;

  for (var i = 0; i<NumColumns; i++){
    for (var j = 0; j<NumRows; j++){

引用我们在上面创建的backgrounds变量.同样,第一个数字是行号,第二个数字是列号.因此,您需要将ij与原来的内容交换.另外,a = 10 值10分配给变量a.要检查是否相等,请使用==.这将检查两个值是否相同.

Reference the backgrounds variable that we created above. Also, the first number is the row number, and the second number is the column number. So you'll want to swap i and j from what you had originally. Also, a = 10 assigns the value of 10 to the variable a. To check for equality, you use ==. This checks if the two values are the same.

      if (backgrounds[j][i] == "#00ff00"){
        c++;
      }

不需要else语句不执行任何操作.您可以省略else部分.

No need to have an else statement that doesn't do anything. You can leave the else part out.

    }
  }
  return c;
}

这篇关于在Google脚本中测试背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:05
查看更多