Class Protection

Protección

Accede a rangos protegidos y hojas de cálculo, y modifícalos. Un rango protegido puede proteger un rango de celdas estático o un rango con nombre. Una hoja protegida puede incluir regiones sin protección. Para las hojas de cálculo creadas con la versión anterior de Hojas de cálculo de Google, usa la clase PageProtection en su lugar.

// Protect range A1:B10, then remove all other users from the list of editors.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect().setDescription('Sample protected range');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}
// Remove all range protections in the spreadsheet that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}
// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Métodos

MétodoTipo de datos que se muestraDescripción breve
addEditor(emailAddress)ProtectionAgrega el usuario determinado a la lista de editores de la hoja o el rango protegidos.
addEditor(user)ProtectionAgrega el usuario determinado a la lista de editores de la hoja o el rango protegidos.
addEditors(emailAddresses)ProtectionAgrega el array determinado de usuarios a la lista de editores de la hoja o el rango protegidos.
addTargetAudience(audienceId)ProtectionAgrega el público objetivo especificado como editor del rango protegido.
canDomainEdit()BooleanDetermina si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar la hoja o el rango protegido.
canEdit()BooleanDetermina si el usuario tiene permiso para editar la hoja o el rango protegido.
getDescription()StringObtiene la descripción de la hoja o el rango protegido.
getEditors()User[]Obtiene la lista de editores de la hoja o el rango protegido.
getProtectionType()ProtectionTypeObtiene el tipo del área protegida, ya sea RANGE o SHEET.
getRange()RangeObtiene el rango que se protege.
getRangeName()StringObtiene el nombre del rango protegido si está asociado a un rango con nombre.
getTargetAudiences()TargetAudience[]Muestra los ID de los públicos objetivo que pueden editar el rango protegido.
getUnprotectedRanges()Range[]Obtiene un array de rangos desprotegidos dentro de una hoja protegida.
isWarningOnly()BooleanDetermina si el área protegida utiliza protección "basada en advertencias".
remove()voidDesprotege el rango o la hoja.
removeEditor(emailAddress)ProtectionQuita al usuario determinado de la lista de editores de la hoja o el rango protegidos.
removeEditor(user)ProtectionQuita al usuario determinado de la lista de editores de la hoja o el rango protegidos.
removeEditors(emailAddresses)ProtectionQuita el array determinado de usuarios de la lista de editores de la hoja o el rango protegidos.
removeTargetAudience(audienceId)ProtectionQuita el público objetivo especificado como editor del rango protegido.
setDescription(description)ProtectionEstablece la descripción de la hoja o el rango protegido.
setDomainEdit(editable)ProtectionEstablece si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar la hoja o el rango protegido.
setNamedRange(namedRange)ProtectionAsocia el rango protegido a un rango con nombre existente.
setRange(range)ProtectionAjusta el rango que se protege.
setRangeName(rangeName)ProtectionAsocia el rango protegido a un rango con nombre existente.
setUnprotectedRanges(ranges)ProtectionDesprotege el array de rangos determinado dentro de una hoja protegida.
setWarningOnly(warningOnly)ProtectionEstablece si este rango protegido usa o no protección "basada en advertencias".

Documentación detallada

addEditor(emailAddress)

Agrega el usuario determinado a la lista de editores de la hoja o el rango protegidos. Este método no le otorga automáticamente permiso al usuario para editar la hoja de cálculo, además, llama a Spreadsheet.addEditor(emailAddress).

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Adds an editor to the spreadsheet using an email address.
// TODO(developer): Replace the email address with a valid email.
ss.addEditor('cloudysanfrancisco@gmail.com');

// Gets a sheet by its name and protects it.
const sheet = ss.getSheetByName('Sheet1');
const sampleProtectedSheet = sheet.protect();

// Adds an editor of the protected sheet using an email address.
// TODO(developer): Replace the email address with a valid email.
sampleProtectedSheet.addEditor('cloudysanfrancisco@gmail.com');

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Parámetros

NombreTipoDescripción
emailAddressStringEs la dirección de correo electrónico del usuario que se agregará.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

addEditor(user)

Agrega el usuario determinado a la lista de editores de la hoja o el rango protegidos. Este método no le otorga automáticamente permiso al usuario para editar la hoja de cálculo, además, llama a Spreadsheet.addEditor(user).

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Adds the active user as an editor of the protected sheet.
sampleProtectedSheet.addEditor(Session.getActiveUser());

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Parámetros

NombreTipoDescripción
userUserEs una representación del usuario que se agregará.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

addEditors(emailAddresses)

Agrega el array determinado de usuarios a la lista de editores de la hoja o el rango protegidos. Este método no otorga automáticamente permiso a los usuarios para editar la hoja de cálculo en sí. Para hacerlo, llama a Spreadsheet.addEditors(emailAddresses).

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Creates variables for the email addresses to add as editors.
// TODO(developer): Replace the email addresses with valid ones.
const TEST_EMAIL_1 = 'cloudysanfrancisco@gmail.com';
const TEST_EMAIL_2 = 'baklavainthebalkans@gmail.com';

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Adds editors to the protected sheet using the email address variables.
sampleProtectedSheet.addEditors([TEST_EMAIL_1, TEST_EMAIL_2]);

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Parámetros

NombreTipoDescripción
emailAddressesString[]Un array de direcciones de correo electrónico de los usuarios que se agregarán.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

addTargetAudience(audienceId)

Agrega el público objetivo especificado como editor del rango protegido.

Parámetros

NombreTipoDescripción
audienceIdStringEl ID del público objetivo que se agregará.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

canDomainEdit()

Determina si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar la hoja o el rango protegido. Muestra una excepción si el usuario no tiene permiso para editar la hoja o el rango protegido.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Logs whether domain users have permission to edit the protected sheet to the console.
console.log(sampleProtectedSheet.canDomainEdit());

Devolvedor

Boolean: Es true si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar la hoja o el rango protegido; si no lo tienen, false.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

canEdit()

Determina si el usuario tiene permiso para editar la hoja o el rango protegido. El propietario de la hoja de cálculo siempre puede editar hojas y rangos protegidos.

// Remove all range protections in the spreadsheet that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}

Devolvedor

Boolean: Es true si el usuario tiene permiso para editar la hoja o el rango protegido; si no lo tiene, false.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getDescription()

Obtiene la descripción de la hoja o el rango protegido. Si no se establece una descripción, este método muestra una cadena vacía.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet and sets the description.
const sampleProtectedSheet = sheet.protect().setDescription('Sample sheet is protected');

// Gets the description of the protected sheet and logs it to the console.
const sampleProtectedSheetDescription = sampleProtectedSheet.getDescription();
console.log(sampleProtectedSheetDescription);

Devolvedor

String: Es la descripción de la hoja o el rango protegido, o una string vacía si no se estableció una descripción.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getEditors()

Obtiene la lista de editores de la hoja o el rango protegido. Muestra una excepción si el usuario no tiene permiso para editar la hoja o el rango protegido.

// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Devolvedor

User[]: Es un array de usuarios con permiso para editar la hoja o el rango protegido.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getProtectionType()

Obtiene el tipo del área protegida, ya sea RANGE o SHEET.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Gets the type of the protected area.
const protectionType = sampleProtectedSheet.getProtectionType();

// Logs 'SHEET'to the console since the type of the protected area is a sheet.
console.log(protectionType.toString());

Devolvedor

ProtectionType: Indica el tipo de área protegida, ya sea RANGE o SHEET.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getRange()

Obtiene el rango que se protege. Si la protección se aplica a la hoja en lugar de a un rango, este método muestra un rango que abarca toda la hoja.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range 'A1:B10' of Sheet1.
const range = sheet.getRange('A1:B10');

// Makes cells A1:B10 a protected range.
const sampleProtectedRange = range.protect();

// Gets the protected ranges on the sheet.
const protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);

// Logs the A1 notation of the first protected range on the sheet.
console.log(protections[0].getRange().getA1Notation());

Devolvedor

Range: Es el rango que se protege.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getRangeName()

Obtiene el nombre del rango protegido si está asociado a un rango con nombre. Muestra null si la protección no está asociada con un rango con nombre. Ten en cuenta que las secuencias de comandos deben llamar de forma explícita a setRangeName(rangeName) para asociar un rango protegido con un rango con nombre. Llamar a Range.protect() para crear una protección desde un Range que es un rango con nombre, sin llamar a setRangeName(rangeName), no es suficiente para asociarlos. Sin embargo, crear un rango protegido a partir de un rango con nombre en la IU de Hojas de cálculo de Google los asocia automáticamente.

// Protect a named range in a spreadsheet and log the name of the protected range.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect();
ss.setNamedRange('Test', range);       // Create a named range.
protection.setRangeName('Test');       // Associate the protection with the named range.
Logger.log(protection.getRangeName()); // Verify the name of the protected range.

Devolvedor

String: Es el nombre del rango con nombre protegido o null si el rango protegido no está asociado con un rango con nombre.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getTargetAudiences()

Muestra los ID de los públicos objetivo que pueden editar el rango protegido.

Devolvedor

TargetAudience[]: Es un array de los IDs de los públicos objetivo.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

getUnprotectedRanges()

Obtiene un array de rangos desprotegidos dentro de una hoja protegida. Si el objeto Protection corresponde a un rango protegido en lugar de a una hoja protegida, este método muestra un array vacío. Si quieres cambiar los rangos desprotegidos, usa setUnprotectedRanges(ranges) para configurar un nuevo array de rangos. Si quieres volver a proteger toda la hoja, configura un array vacío.

// Unprotect cells E2:F5 in addition to any other unprotected ranges in the protected sheet.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect();
var unprotected = protection.getUnprotectedRanges();
unprotected.push(sheet.getRange('E2:F5'));
protection.setUnprotectedRanges(unprotected);

Devolvedor

Range[]: Es un array de rangos sin protección dentro de una hoja protegida.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

isWarningOnly()

Determina si el área protegida utiliza protección "basada en advertencias". La protección basada en advertencias implica que todos los usuarios pueden editar datos en el área, excepto que esta acción le solicita al usuario que confirme la edición. De forma predeterminada, las hojas o los rangos protegidos no se basan en advertencias. Para cambiar al estado de advertencia, usa setWarningOnly(warningOnly).

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit')

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Sets the warning status for the protected sheet as true.
sampleProtectedSheet.setWarningOnly(true);

const protectedSheetWarningStatus = sampleProtectedSheet.isWarningOnly();

// Logs the warning status of the protected sheet to the console.
console.log(protectedSheetWarningStatus);

Devolvedor

Boolean: Es true si la hoja o el rango protegido solo usa protección basada en advertencias.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

remove()

Desprotege el rango o la hoja.

// Remove all range protections in the spreadsheet that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}
// Remove sheet protection from the active sheet, if the user has permission to edit it.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0];
if (protection && protection.canEdit()) {
  protection.remove();
}

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

removeEditor(emailAddress)

Quita al usuario determinado de la lista de editores de la hoja o el rango protegidos. Ten en cuenta que, si el usuario es miembro de un Grupo de Google que tiene permiso de edición, o si todos los usuarios del dominio tienen permiso de edición, el usuario aún puede editar el área protegida. Ni el propietario de la hoja de cálculo ni el usuario actual pueden eliminarse.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Creates a variable for an email address.
// TODO(developer): Replace the email address with a valid one.
const TEST_EMAIL = 'baklavainthebalkans@gmail.com';

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Adds an editor to the protected sheet using the email address variable.
sampleProtectedSheet.addEditor(TEST_EMAIL);

// Removes the editor from the protected sheet using the email address variable.
sampleProtectedSheet.removeEditor(TEST_EMAIL);

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Parámetros

NombreTipoDescripción
emailAddressStringEs la dirección de correo electrónico del usuario que se quitará.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

removeEditor(user)

Quita al usuario determinado de la lista de editores de la hoja o el rango protegidos. Ten en cuenta que, si el usuario es miembro de un Grupo de Google que tiene permiso de edición, o si todos los usuarios del dominio tienen permiso de edición, el usuario también puede editar el área protegida. No se pueden quitar ni el propietario de la hoja de cálculo ni el usuario actual.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Removes the active user from the editors of the protected sheet.
sampleProtectedSheet.removeEditor(Session.getActiveUser());

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Parámetros

NombreTipoDescripción
userUserEs una representación del usuario que se quitará.

Devolvedor

Protection: Es el objeto que representa la configuración de protección para el encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

removeEditors(emailAddresses)

Quita el array determinado de usuarios de la lista de editores de la hoja o el rango protegidos. Ten en cuenta que si alguno de los usuarios es miembro de un Grupo de Google que tiene permiso de edición, o si todos los usuarios del dominio tienen permiso de edición, esos usuarios aún pueden editar el área protegida. No se pueden quitar ni el propietario de la hoja de cálculo ni el usuario actual.

// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Parámetros

NombreTipoDescripción
emailAddressesString[]Un array de direcciones de correo electrónico de los usuarios que se quitarán.

Devolvedor

Protection: Es el objeto que representa la configuración de protección para el encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

removeTargetAudience(audienceId)

Quita el público objetivo especificado como editor del rango protegido.

Parámetros

NombreTipoDescripción
audienceIdStringEs el ID del público objetivo que se quitará.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setDescription(description)

Establece la descripción de la hoja o el rango protegido.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets the sheet 'Sheet1' by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Sets the sheet description to 'Sheet1 is protected.'
sampleProtectedSheet.setDescription('Sheet1 is protected');

// Gets the description of the protected sheet.
const sampleProtectedSheetDescription = sampleProtectedSheet.getDescription();

// Logs the description of the protected sheet to the console.
console.log(sampleProtectedSheetDescription);

Parámetros

NombreTipoDescripción
descriptionStringLa descripción de la hoja o el rango protegido.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setDomainEdit(editable)

Establece si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar la hoja o el rango protegido. Ten en cuenta que cualquier usuario que tenga permiso de edición explícito puede editar el área protegida, independientemente de esta configuración. Muestra una excepción si la hoja de cálculo no pertenece a un dominio de Google Workspace (es decir, si es propiedad de una cuenta gmail.com).

Parámetros

NombreTipoDescripción
editableBooleanEs true si todos los usuarios del dominio propietario de la hoja de cálculo deben tener permiso para editar la hoja o el rango protegido; si no lo es, false.

Devolvedor

Protection: Es el objeto que representa la configuración de protección para el encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setNamedRange(namedRange)

Asocia el rango protegido a un rango con nombre existente. Si el rango con nombre abarca un área diferente del rango protegido actual, este método mueve la protección para cubrir el rango con nombre. El rango con nombre debe estar en la misma hoja que el rango protegido actual. Ten en cuenta que las secuencias de comandos deben llamar explícitamente a este método para asociar un rango protegido con un rango con nombre; llamar a Range.protect() para crear una protección desde un Range que es un rango con nombre, sin llamar a setRangeName(rangeName), no es suficiente para asociarlos. Sin embargo, crear un rango protegido a partir de un rango con nombre en la IU de Hojas de cálculo de Google los asocia automáticamente.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Protects cells A1:D10 on Sheet1.
const sheet = ss.getSheetByName('Sheet1');
const protectedRange = sheet.getRange('A1:D10').protect();

// Logs the current protected range, A1:D10.
console.log(protectedRange.getRange().getA1Notation());

// Creates a named range for cells E1:J10 called 'NewRange.'
const newRange = sheet.getRange('E1:J10');
ss.setNamedRange('NewRange', newRange);
const namedRange = ss.getNamedRanges()[0];

// Updates the protected range to the named range, 'NewRange.'
// This updates the protected range on Sheet1 from A1:D10 to E1:J10.
protectedRange.setNamedRange(namedRange);

// Logs the updated protected range to the console.
console.log(protectedRange.getRange().getA1Notation());

Parámetros

NombreTipoDescripción
namedRangeNamedRangeEl rango con nombre existente que se asociará con el rango protegido.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setRange(range)

Ajusta el rango que se protege. Si el rango dado abarca un área diferente del rango protegido actual, este método mueve la protección para cubrir el rango nuevo.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Protects cells A1:D10 on Sheet1 of the spreadsheet.
const sheet = ss.getSheetByName('Sheet1');
const protectedRange = sheet.getRange('A1:D10').protect();

// Logs the original protected range, A1:D10, to the console.
console.log(protectedRange.getRange().getA1Notation());

// Gets the range E1:J10.
const newRange = sheet.getRange('E1:J10');

// Updates the protected range to E1:J10.
protectedRange.setRange(newRange);

// Logs the updated protected range to the console.
console.log(protectedRange.getRange().getA1Notation());

Parámetros

NombreTipoDescripción
rangeRangeEl nuevo rango que se debe proteger contra las modificaciones.

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setRangeName(rangeName)

Asocia el rango protegido a un rango con nombre existente. Si el rango con nombre abarca un área diferente del rango protegido actual, este método mueve la protección para cubrir el rango con nombre. El rango con nombre debe estar en la misma hoja que el rango protegido actual. Ten en cuenta que las secuencias de comandos deben llamar explícitamente a este método para asociar un rango protegido con un rango con nombre; llamar a Range.protect() para crear una protección desde un Range que es un rango con nombre, sin llamar a setRangeName(rangeName), no es suficiente para asociarlos. Sin embargo, crear un rango protegido a partir de un rango con nombre en la IU de Hojas de cálculo de Google los asocia automáticamente.

// Protect a named range in a spreadsheet and log the name of the protected range.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect();
ss.setNamedRange('Test', range);       // Create a named range.
protection.setRangeName('Test');       // Associate the protection with the named range.
Logger.log(protection.getRangeName()); // Verify the name of the protected range.

Parámetros

NombreTipoDescripción
rangeNameStringEl nombre del rango con nombre que se protegerá.

Devolvedor

Protection: Es el objeto que representa la configuración de protección para el encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setUnprotectedRanges(ranges)

Desprotege el array de rangos determinado dentro de una hoja protegida. Muestra una excepción si el objeto Protection corresponde a un rango protegido en lugar de a una hoja protegida o si alguno de los rangos no está en la hoja protegida. Para cambiar los rangos desprotegidos, configura un nuevo array de rangos. Si quieres volver a proteger toda la hoja, configura un array vacío.

// Protect the active sheet except B2:C5, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');
var unprotected = sheet.getRange('B2:C5');
protection.setUnprotectedRanges([unprotected]);

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Parámetros

NombreTipoDescripción
rangesRange[]Array de rangos que se deben dejar sin protección dentro de una hoja protegida.

Devolvedor

Protection: Es el objeto que representa la configuración de protección para el encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets

setWarningOnly(warningOnly)

Establece si este rango protegido usa o no protección "basada en advertencias". La protección basada en advertencias implica que todos los usuarios pueden editar datos en el área, excepto que esta acción solicita una advertencia en la que se solicita al usuario que confirme la edición. De forma predeterminada, las hojas o los rangos protegidos no se basan en advertencias. Para verificar el estado de advertencia, usa isWarningOnly().

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets the sheet 'Sheet1' by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet and sets the protection to warning-based.
const sampleProtectedSheet = sheet.protect().setWarningOnly(true);

// Logs whether the protected sheet is warning-based to the console.
console.log(sampleProtectedSheet.isWarningOnly());

Parámetros

NombreTipoDescripción
warningOnlyBoolean

Devolvedor

Protection: Es el objeto que representa la configuración de protección del encadenamiento.

Autorización

Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes alcances:

  • https://www.googleapis.com/auth/spreadsheets.currentonly
  • https://www.googleapis.com/auth/spreadsheets