18
votes

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.

8

8 Answers

24
votes

UPDATE(April 2019)

You can now directly insertCheckboxes(or removeCheckboxes) on a Range or RangeList without any workarounds. You can also change the checked value/unchecked value using alternate method signatures found in the documentation.

Snippet:

SpreadsheetApp.getActive()
    .getRange('Sheet2!A2:A10')
    .insertCheckboxes();
19
votes

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);
}
16
votes

You want to create the checkbox in the cells of spreadsheet using the scripts. If my understanding is correct, how about this workaround? Unfortunately, the Class SpreadsheetApp has no methods for creating the checkbox yet. (When such methods are tried to be used, the error occurs.) So I would like to propose to create it using Sheets API.

When I saw ConditionType of dataValidation, the document of BOOLEAN says

The cell's value must be TRUE/FALSE or in the list of condition values. Supported by data validation. Renders as a cell checkbox. ...

From this, I could understand how to create the checkbox using Sheets API. The following script is a sample script. This creates 6 checkboxes to "A1:C3". When you use this script, please enable Sheets API at Advanced Google Services and API console as follows.

Enable Sheets API v4 at Advanced Google Services

  • On script editor
    • Resources -> Advanced Google Services
    • Turn on Google Sheets API v4

Enable Sheets API v4 at API console

  • On script editor
    • Resources -> Cloud Platform project
    • View API console
    • At Getting started, click Enable APIs and get credentials like keys.
    • At left side, click Library.
    • At Search for APIs & services, input "sheets". And click Google Sheets API.
    • Click Enable button.
    • If API has already been enabled, please don't turn off.

If now you are opening the script editor with the script for using Sheets API, you can enable Sheets API for the project by accessing this URL https://console.cloud.google.com/apis/library/sheets.googleapis.com/

Sample script :

In this sample script, the checkboxes are created to "A1:C3" of Sheet1. Please use this script as the container-bound script.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getSheetByName("Sheet1").getSheetId();
var resource = {"requests": [
  {
    "repeatCell": {
      "cell": {"dataValidation": {"condition": {"type": "BOOLEAN"}}},
      "range": {"sheetId": sheetId, "startRowIndex": 0, "endRowIndex": 3, "startColumnIndex": 0, "endColumnIndex": 3},
      "fields": "dataValidation"
    }
  },
  {
    "updateCells": {
      "rows": [
        {"values": [{"userEnteredValue": {"boolValue": true}}, {"userEnteredValue": {"boolValue": false}}, {"userEnteredValue": {"boolValue": false}}]},
        {"values": [{"userEnteredValue": {"boolValue": true}}, {"userEnteredValue": {"boolValue": true}}, {"userEnteredValue": {"boolValue": false}}]},
        {"values": [{"userEnteredValue": {"boolValue": true}}, {"userEnteredValue": {"boolValue": true}}, {"userEnteredValue": {"boolValue": true}}]}
      ],
      "start": {"rowIndex": 0, "columnIndex": 0, "sheetId": sheetId},
      "fields": "userEnteredValue"
    }
  }
]};
Sheets.Spreadsheets.batchUpdate(resource, ss.getId());
  1. dataValidation is set using repeatCell.
  2. boolValue is set using updateCells.

Result :

enter image description here

Note :

  • This is a simple sample script. So please modify this for your environment.
  • When the methods of the Class SpreadsheetApp for creating the checkbox can be used, I think that the following sample script might be able to be used.

At June 22, 2018, this script returns an error of the server error yet.

var rule = SpreadsheetApp.newDataValidation().withCriteria(SpreadsheetApp.DataValidationCriteria.CHECKBOX, ["TRUE", "FALSE"]).build();
SpreadsheetApp.getActiveSheet().getRange("A1").setDataValidation(rule);

References :

If I misunderstand your question, I'm sorry.

4
votes

The checkbox is the recently added Data Validation criterion. Interestingly enough, when I attempt to call the 'getDataValidation()' method on the range that contains checkboxes, the following error is thrown:

var rule = range.getDataValidation();

We're sorry, a server error occurred. Please wait a bit and try again.

In the meantime, you can work around this by placing a single checkbox somewhere in your sheet and copying its Data Validation to the new range. For example, if "A1" is the cell containing the checkbox and the target range consists of a single column with 3 rows:

var range = sheet.getRange("A1"); //checkbox template cell
var targetRange = sheet.getRange(rowIdex, colIndex, numOfRows, numOfCols);
range.copyTo(col, SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION);
var values = [["true"], ["false"], ["false"]];
targetRange.setValues(values);
4
votes

Short answer

Add the checkbox from the Google Sheets UI, then use one of the copyTo methods of Class Range.

Explanation

The Google Apps Script Spreadsheet service doesn't include a methods for everything that could be done through the Google Sheets user interface. This is the case of the Insert > Checkbox which is a pretty new feature.

Even the Record macro feature can't do this. The following was recorded one momento ago

/** @OnlyCurrentDoc */

function InsertCheckbox() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  /*
   * Added to show the missing Insert > Checkbox step
   */
  spreadsheet.getRange('B1').activate();
  spreadsheet.getRange('A1').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

NOTE: If you don't want to pass all the cell properties (borders, formulas, background, etc. instead of SpreadsheetApp.CopyPasteType.PASTE_NORMAL use SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION.

Related Q on Stack Overflow

2
votes
function onEdit() {
var cell = SpreadsheetApp.getActive().getRange('A1');
      var array =['☐','☑'];
    // var rule = SpreadsheetApp.newDataValidation().requireValueInList(['☐','☑']).build();
      var rule = SpreadsheetApp.newDataValidation().requireValueInList(array, false).build()
     cell.setDataValidation(rule);
     var valor = array[1];
     // Logger.log(valor);
      if(cell.getValue() == valor){
        cell.offset(0, 1).setValue("Aprobado");
      } else{
        cell.offset(0, 1).setValue("Reprobado");
      }
    }
2
votes

Easy:

//There are two ways, using Range or using current cell or sheet or similar 
//First is using current cell
function VoF() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getCurrentCell().offset(1, 0, 499, 1).setDataValidation(SpreadsheetApp.newDataValidation()
  .setAllowInvalid(true)
  .setHelpText('TRUE or FALSE')
  .requireCheckbox() //if you customize this is possible that you dont get the boxes and the verification data could fail,so keep them standar with TRUE and FALSE
  .build());
};

//Second is using Spreedsheet ranges

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('G1:G11').activate();
  spreadsheet.getRange('G1:G11').setDataValidation(SpreadsheetApp.newDataValidation()
  .setAllowInvalid(false)
  .requireCheckbox()
  .build());
};
-1
votes

I agree that you have to workaround to create a checkbox. Another way maybe is to create a dropdown list.

function myFunction() {
 var cell = SpreadsheetApp.getActive().getRange('A1');
 var rule = SpreadsheetApp.newDataValidation().requireValueInList(['☐','☑']).build();
 cell.setDataValidation(rule);
}