【问题标题】:How to get next empty cell position in a specific column, Google Apps Script如何获取特定列中的下一个空单元格位置,Google Apps 脚本
【发布时间】:2019-11-11 03:47:28
【问题描述】:

我正在构建一个应用程序脚本来处理电子表格中的现有数据,并根据现有数据构建新的数据列。如何在任何给定列中找到下一个空单元格(不是最后一个单元格)?

这是我最初编写的代码。

function isempty(x, y){
  alert(SpreadsheetApp.getActiveSheet().getRange(y, x).isBlank());
    return SpreadsheetApp.getActiveSheet().getRange(y, x).isBlank();
}
function nextopencell(column){
  var x = 0;
  var b = 1;
  while(b != 2){
   x++;
   var data = isempty(x, column);
    if(data == true){
      b = 2;
    }
  }
  alert(x);
return x;
}

当一列中有 5 个非空单元格,其中第一个是列中的第一个单元格时,我希望返回值为 6,但无论实际状态如何,函数都会返回 3(非空,空) 列中的单元格。
任何帮助将不胜感激。

【问题讨论】:

标签: google-apps-script google-sheets


【解决方案1】:

Sheet.getRange() 期望行在前,列在后,所以在你的getRange() 调用中翻转xy

function isempty(x, y) {
  alert(SpreadsheetApp.getActiveSheet().getRange(x, y).isBlank());
  return SpreadsheetApp.getActiveSheet().getRange(x, y).isBlank();
}

另外,请阅读 Apps 脚本 Best Practices 并考虑改进脚本的方法。例如,在上面的 sn-p 中,您执行了两次isBlank(),但您只需要执行一次。

【讨论】:

  • 成功了!非常感谢!是的,我知道我这样做只是为了调试我的代码。
【解决方案2】:

对于您打算做的事情,这是一种不同的方法。在我的代码中,我使用的是.getDataRange() 方法。这将获取工作表中的所有数据,然后使用 for 循环,您可以遍历所有行并使用 column 参数从您想要的值的列中指定.

function nextopencell(column){

  // Get the active spreadsheet and sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];

  // This represents ALL the data
  var range = sheet.getDataRange();
  var values = range.getValues();

  // Build a new array to fill it with the desire data
  var newColArray = [];

  // Iterate over all rows
  for (var i = 0; i < values.length; i++) {
    // With the column we specify in what column we want to extract the data
    if (values[i][column]) {
       // fill array
       newColArray.push(values[i][column]);
    } else{
       // Show what cells are empty
       Logger.log("This is an empty cell at column " + (column+1).toString() + " and row " + (i+1).toString());
    }
  }

  // This is the built array to fill a new column as you want
  Logger.log(newColArray);

}

更多信息,您可以查看this

【讨论】:

  • 谢谢。我一直在阅读有关在 Apps 脚本中使用数组的内容,您的示例肯定巩固了我一直在阅读的内容。
  • 小心.getDataRange(),因为它只会返回“可见”数据。被隐藏/过滤掉的列/行将不会被返回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多