Home > Software design >  How to set a named range for a data validation programmatically (in Google apps script) in a Google
How to set a named range for a data validation programmatically (in Google apps script) in a Google

Time:06-24

Use Case

Example. I have a named range Apples (address "Sheet10!B2:B"), which in use for data validation for plenty of sheet cells. The data range for Apples can be changed (in a script), e.g. to "Sheet10!D2:D".

It works from UI

I can set manually a named range as a data source of data validation. In this case, the data validation of a cell will always refer to the named range Apples with updated the data range.

How to make it in Google Apps Script?

GAS Limits

The code, for setting data validation, should look like this, if you have a RamedRange object:

      mySheet.getRange('F5')
        .setDataValidation(
          SpreadsheetApp.newDataValidation()
            .requireValueInRange(
              namedRange.getRange()
            )
            .setAllowInvalid(false)
            .build()
        );

DataValidationBuilder.requireValueInRange() does not work here as it requires only class Range (it cannot get NamedRange), and no reference to a named range will be used.

Is there a workaround or so?

UPD1 - Spreadsheet.getRangeByName() does not work

Getting range by name does not help, the data validation will get actual range address. SpreadsheetApp.getActive().getRangeByName("Apples")

UPD2 No way to make it so far in GAS

As @TheMaster posted, it's not possible at this moment.

Please set 1 for posts:

P.S. It looks like the only solution will work is Google Sheets API.

CodePudding user response:

Use getRangeByName()

function lfunko() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  var cell = sh.getRange(1, 10);//location where datavalidation is applied
  var rule = SpreadsheetApp.newDataValidation().requireValueInRange(ss.getRangeByName("MyList")).build();
  cell.setDataValidation(rule);
}

CodePudding user response:

Currently, This seems to be impossible. This is however a known issue. 1 this feature request, if you want this implemented.

https://issuetracker.google.com/issues/143913035

Workarounds from the tracker issue creator:

If a validation rule is manually created with a NamedRange via the Sheets GUI, it can then be copied programmatically using Range.getDataValidations(), and subsequently used to programmatically create new DataValidations. DataValidations created this way maintain their connection to the NamedRange, and behave like their manually created counterparts. This demonstrates that the functionality to 'use' NamedRanges for data validation rules is already possible with Apps Scripts, but not the option to 'create' them.

  • Related