简体   繁体   English

如何检查Google表格数组中单元格中的值?

[英]How can I check a value in a cell in an array Google Sheets?

I want to calculate how many Y's & N's appear in an array / range defined: 我想计算在定义的数组/范围中出现多少个Y和N:

Cell Range: D4:D42 单元格范围: D4:D42

function myFunction() {
 var count = SpreadsheetApp.getActiveSheet().getRange(5, 3, 40, 1);
 var numRows = count.getNumRows();
 var numCols = count.getNumColumns();
 var y = 0;
 var n = 0;

 for (var i = 1; i <= numRows; i++) {
  for (var j = 1; j <= numCols; j++) {
   var currentValue = count.getCell(i, j).getValue();
   if (currentValue = "y") {
    y = y + 1;
   } else if (currentValue = "n") {
    n = n + 1;
   }
  }
 }
 Browser.msgBox("There are " + y + " paid & " + n + " not paid");
}

This returns 40 Y's and 0 N's 这将返回40 Y和0 N

Not sure what I am doing wrong here but I think it's a simple fix! 不知道我在这里做错了什么,但我认为这很简单!

The problem is in this line: 问题在这一行:

if (currentValue = "y") {

You are assigning "y" to currentValue. 您正在将“ y”分配给currentValue。 To actually check for equality, you should try the "===" operator. 要实际检查是否相等,应尝试使用“ ===”运算符。 Try this and see if it solves your problem: 试试看,看看是否能解决您的问题:

function myFunction() {
    var count = SpreadsheetApp.getActiveSheet().getRange(5, 4, 39, 1);
    var numRows = count.getNumRows();
    var numCols = count.getNumColumns();
    var y = 0;
    var n = 0;

    for (var i = 1; i <= numRows; i++) {
        for (var j = 1; j <= numCols; j++) {
            var currentValue = count.getCell(i, j).getValue();
            if (currentValue === "y") {
                y = y + 1;
            } else if (currentValue === "n") {
                n = n + 1;
            }
        }
    }
    Browser.msgBox("There are " + y + " paid & " + n + " not paid");
}

I also updated the getRange() parameters to match D4:D42. 我还更新了getRange()参数以匹配D4:D42。 In your code, they matched C5:C44. 在您的代码中,它们匹配了C5:C44。 See the getRange() function documentation . 请参阅getRange()函数文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM