在最后一个空行中添加值(n + 1)

时间:2017-04-15 14:26:30

标签: javascript google-apps-script google-sheets

我遇到了问题,我不知道Google电子表格中的创建按钮如何找到最后一个空行并在第一列中添加下一个数字(n + 1)和第二列实际日期。

function selectFirstEmptyRow() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  sheet.setActiveSelection(sheet.getRange("A" + getFirstEmptyRowWholeRow()))
  // copy value from row
  var ss = SpreadsheetApp.getActiveSheet();

  ss.insertRowAfter(ss.getLastRow());
  ss.getRange(1, 1).copyTo(ss.getRange(ss.getLastRow() + 1, 1));

  // add 1
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeRange = ss.getActiveRange();
  var cell, cellValue, cellFormula;

  // iterate through all cells in the active range
  for (var cellRow = 1; cellRow <= activeRange.getHeight(); cellRow++) {
    for (var cellColumn = 1; cellColumn <= activeRange.getWidth(); cellColumn++) {
      cell = activeRange.getCell(cellRow, cellColumn);
      cellFormula = cell.getFormula();

      if (cellFormula[0] != "=") {
        cellValue = cell.getValue();
        cell.setValue(cellValue + 1);
      }
    }
  }
}

function getFirstEmptyRowWholeRow() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var values = range.getValues();
  var row = 3;
  for (var row = 3; row < values.length; row++) {
    if (!values[row].join("")) break;
  }
  return (row + 1);
}

1 个答案:

答案 0 :(得分:0)

您可以向Google电子表格添加自定义菜单:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My menu')
      .addItem('Add new date row', 'insertAtNextEmptyRow')
      .addToUi();
}

function insertAtNextEmptyRow() {
  var firstRow = 3;

  var sheet = SpreadsheetApp.getActiveSheet();
  var row = getNextEmptyRow(firstRow);
  var previousNum = SpreadsheetApp.getActiveSheet().getRange('A' + (row - 1)).getValue()
  if (previousNum !== parseInt(previousNum, 10))
    previousNum = row - firstRow - 1;
  SpreadsheetApp.getActiveSheet().getRange('A' + row).setValue(previousNum + 1);
  var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
  SpreadsheetApp.getActiveSheet().getRange('B' + row).setValue(date);
}

function getNextEmptyRow(firstRow) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var values = range.getValues();

  for (var row = firstRow; row < values.length; row++) {
    if (!values[row].join("")) 
      return (row + 1);
  }
  return null;
}

以下是它的样子:

enter image description here