Placing checkboxes in Google Sheets using Apps Scr

2019-01-19 22:14发布

I know that checkbox is a relatively new feature in Google Sheets, so I'm trying to find a way to automatically create checkboxes in cells.

So far I haven't found a reference regarding this in Google Apps Script documentation.

Currently I'm doing it manually but any suggestion using script will be much appreciated.

7条回答
放荡不羁爱自由
2楼-- · 2019-01-19 22:59

I'm not sure when they did it, but they've added this now. Use class DataValidationBuilder's requireCheckbox() method. Example:

function setCheckboxes() {
  // Assumes there's only one sheet
  var sheet = SpreadsheetApp.getActiveSheet();

  // This represents ALL the data
  var dataRange = sheet.getDataRange();

  /* Get checkbox range from sheet data range. Assumes checkboxes are on the
  left-most column
  */
  var dataRangeRow = dataRange.getRow();
  var dataRangeColumn = dataRange.getColumn();
  var dataRangeLastRow = dataRange.getLastRow();
  var checkboxRange = sheet.getRange(
    dataRangeRow,
    dataRangeColumn,
    dataRangeLastRow
  );

  var enforceCheckbox = SpreadsheetApp.newDataValidation();
  enforceCheckbox.requireCheckbox();
  enforceCheckbox.setAllowInvalid(false);
  enforceCheckbox.build();

  checkboxRange.setDataValidation(enforceCheckbox);
}
查看更多
登录 后发表回答