Google表格脚本计数公式

时间:2018-01-31 16:49:37

标签: google-apps-script google-sheets

我已经为此找到了解决方案,但我发现的所有解决方案似乎都比我需要的更先进。我正在寻找的是一种了解A列中有多少单元格的方法。我不想在表格中使用公式,我希望能够在飞行中计算出答案'在我的剧本中。

这可能吗?

2 个答案:

答案 0 :(得分:0)

嗯,你可以试试这样的事情

var sheet = SpreadsheetApp.openById(SPREADSHEET_ID)
    .getSheetByName(SHEET_NAME);
var range = sheet.getRange(startingCellRow, startingCellColumn, noOfRows, noOfColumns);
var datas = range.getValues();
var count = 0;
for (data in datas) {
    for (cell in data) {
        if (!(typeof cell === "undefined")) {
            count++;
        }
    }
}
Logger.log(count)

有人需要公式:

=COUNTIF(<start_cell>:<end_cell>; "<>")

例如:=COUNTIF(A1:A10; "<>")

完整参考和致谢:

google docs count cells that contain any text

count empty values in array

答案 1 :(得分:0)

如果您想要短片,可以利用Array.filter()

var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getRange('A:A').getValues().flatten();
// Filters data to return an array of empty values and counts them
var count = data.filter(function(e) { return e[0] == ""; }).length;

Array.prototype.flatten = function() {
  return this.join('@').split('@');
};

编辑2: 对不起,您实际上想知道填充了多少,所以:

var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getRange('A:A').getValues().flatten();
// Filters data to return an array of 'truthy' values and counts them
var count = data.filter(Boolean).length;

Array.prototype.flatten = function() {
  return this.join('@').split('@');
};

修改3:代码段

&#13;
&#13;
Array.prototype.flatten = function() {
  return this.join('@').split('@');
};

// Simulates column array returned from getValues()
var colSampleArray = [[1],[],[],[""],[],[2],[],[],[""],[3],[],[4],[],[5],[]];
// Converts 2D Array into Plain Array
var data = colSampleArray.flatten();
// Filters data to return an array of 'truthy' values and counts them
var count = data.filter(Boolean).length;
window.alert(count);
&#13;
&#13;
&#13;