如何获取活动行中的第一个单元格?

时间:2013-11-30 01:47:00

标签: google-apps-script google-sheets

如果我希望我的Google Apps脚本应用获取电子表格中当前选定的行,我会使用以下内容:

function getCurrentRow() {
  var currentRow = SpreadsheetApp.getActiveSheet().getActiveSelection().getRowIndex();
  return currentRow;
}

但是,如果我想获得此行中的第一个单元格(在其中添加注释)该怎么办?

3 个答案:

答案 0 :(得分:2)

您可以使用getCell()方法(https://developers.google.com/apps-script/reference/spreadsheet/range#getCell(Integer,Integer)

function getFirstCell() {
  var firstCell= SpreadsheetApp.getActiveSheet().getActiveSelection().getCell(1,1);
  return firstCell;
}

答案 1 :(得分:1)

您可以使用offset获取相对于有效范围的范围。

function getFirstCellInRow() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var activeCell = sheet.getActiveCell();
  var firstCell = activeCell.offset(0, 1-activeCell.getColumn());
  return firstCell;
}

或者只使用getRange(A1notation),从您拥有的内容开始:

function getFirstCellInRow2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var currentRow = sheet.getActiveSelection().getRowIndex();
  return sheet.getRange("A"+currentRow);
}

要写入行中的第一个单元格:

getFirstCellInRow().setValue('Tada');

答案 2 :(得分:0)

以下脚本将在A列的第一行中插入“我的信息”。

function FirstCellColumnA() {
  // replace with destination ID
  var s = SpreadsheetApp.openById('spreadsheetID');

  // replace with destination Sheet tab name
  var ss = s.getSheetByName('sheetname');

  // In Column A first ROW Available ss.getLastRow()+1 = find the
  // first row available, 1 = start in column 1, 1 = rows to start,
  // 1 = column where to put the data.
  ss.getRange(ss.getLastRow() + 1, 1, 1, 1).setValue('My Info');
}

我希望这对你有所帮助。