Acceder a rangos y hojas protegidos y modificarlos Un rango protegido puede proteger un rango estático de celdas 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 en su lugar.
Page
// Protect range A1:B10, then remove all other users from the list of editors. const ss = SpreadsheetApp.getActive(); const range = ss.getRange('A1:B10'); const 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. const 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. const ss = SpreadsheetApp.getActive(); const protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE); for (let i = 0; i < protections.length; i++) { const protection = protections[i]; if (protection.canEdit()) { protection.remove(); } }
// Protect the active sheet, then remove all other users from the list of // editors. const sheet = SpreadsheetApp.getActiveSheet(); const 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. const me = Session.getEffectiveUser(); protection.addEditor(me); protection.removeEditors(protection.getEditors()); if (protection.canDomainEdit()) { protection.setDomainEdit(false); }
Métodos
| Método | Tipo de datos que se muestra | Descripción breve |
|---|---|---|
add | Protection | Agrega el usuario especificado a la lista de editores de la hoja o el rango protegidos. |
add | Protection | Agrega el usuario especificado a la lista de editores de la hoja o el rango protegidos. |
add | Protection | Agrega el array de usuarios proporcionado a la lista de editores de la hoja o el rango protegidos. |
add | Protection | Agrega el público objetivo especificado como editor del rango protegido. |
can | Boolean | Determina si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar el rango o la hoja protegidos. |
can | Boolean | Determina si el usuario tiene permiso para editar el rango o la hoja protegidos. |
get | String | Obtiene la descripción de la hoja o el rango protegidos. |
get | User[] | Obtiene la lista de editores del rango o la hoja protegidos. |
get | Protection | Obtiene el tipo de área protegida, ya sea RANGE o SHEET. |
get | Range | Obtiene el rango que se protege. |
get | String|null | Obtiene el nombre del rango protegido si está asociado a un rango con nombre. |
get | Target | Devuelve los IDs de los públicos objetivo que pueden editar el rango protegido. |
get | Range[] | Obtiene un array de rangos sin protección dentro de una hoja protegida. |
is | Boolean | Determina si el área protegida usa la protección "basada en advertencias". |
remove() | void | Quita la protección del rango o la hoja. |
remove | Protection | Quita al usuario indicado de la lista de editores de la hoja o el rango protegidos. |
remove | Protection | Quita al usuario indicado de la lista de editores de la hoja o el rango protegidos. |
remove | Protection | Quita el array de usuarios determinado de la lista de editores de la hoja o el rango protegidos. |
remove | Protection | Quita el público objetivo especificado como editor del rango protegido. |
set | Protection | Establece la descripción del rango o la hoja protegidos. |
set | Protection | Establece si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar el rango o la hoja protegidos. |
set | Protection | Asocia el rango protegido con un rango con nombre existente. |
set | Protection | Ajusta el rango que se protege. |
set | Protection | Asocia el rango protegido con un rango con nombre existente. |
set | Protection | Quita la protección del array de rangos determinado dentro de una hoja protegida. |
set | Protection | Establece si este rango protegido usa o no la protección "basada en advertencias". |
Documentación detallada
add Editor(emailAddress)
Agrega el usuario especificado a la lista de editores de la hoja o el rango protegidos. Este método no otorga automáticamente permiso al usuario para editar la hoja de cálculo. Para ello, 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
| Nombre | Tipo | Descripción |
|---|---|---|
email | String | Es la dirección de correo electrónico del usuario que se agregará. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
add Editor(user)
Agrega el usuario especificado a la lista de editores de la hoja o el rango protegidos. Este método no otorga automáticamente permiso al usuario para editar la hoja de cálculo. Para ello, 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
| Nombre | Tipo | Descripción |
|---|---|---|
user | User | Es una representación del usuario que se agregará. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
add Editors(emailAddresses)
Agrega el array de usuarios proporcionado a la lista de editores de la hoja o el rango protegidos. Este método no otorga automáticamente a los usuarios permiso para editar la hoja de cálculo; para ello, 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
| Nombre | Tipo | Descripción |
|---|---|---|
email | String[] | Es un array de direcciones de correo electrónico de los usuarios que se agregarán. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
add Target Audience(audienceId)
Agrega el público objetivo especificado como editor del rango protegido.
Parámetros
| Nombre | Tipo | Descripción |
|---|---|---|
audience | String | Es el ID del público objetivo que se agregará. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
can Domain Edit()
Determina si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar el rango o la hoja protegidos. Arroja una excepción si el usuario no tiene permiso para editar el rango protegido o 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'); // 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());
Volver
Boolean: true si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar el rango o la hoja protegidos; false si no lo tienen.
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
can Edit()
Determina si el usuario tiene permiso para editar el rango o la hoja protegidos. El propietario de la hoja de cálculo siempre puede editar los rangos y las hojas protegidos.
// Remove all range protections in the spreadsheet that the user has permission // to edit. const ss = SpreadsheetApp.getActive(); const protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE); for (let i = 0; i < protections.length; i++) { const protection = protections[i]; if (protection.canEdit()) { protection.remove(); } }
Volver
Boolean: true si el usuario tiene permiso para editar el rango o la hoja protegidos; false si no lo tiene
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
get Description()
Obtiene la descripción de la hoja o el rango protegidos. Si no se establece ninguna descripción, este método devuelve 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);
Volver
String: Es la descripción del rango o la hoja protegidos, o una cadena vacía si no se estableció ninguna 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
get Editors()
Obtiene la lista de editores del rango o la hoja protegidos. Arroja una excepción si el usuario no tiene permiso para editar el rango o la hoja protegidos.
// Protect the active sheet, then remove all other users from the list of // editors. const sheet = SpreadsheetApp.getActiveSheet(); const 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. const me = Session.getEffectiveUser(); protection.addEditor(me); protection.removeEditors(protection.getEditors()); if (protection.canDomainEdit()) { protection.setDomainEdit(false); }
Volver
User[]: Es un array de usuarios con permiso para editar el rango o la hoja protegidos.
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
get Protection Type()
Obtiene el tipo de á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());
Volver
Protection: Es 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
get Range()
Obtiene el rango que se protege. Si la protección se aplica a la hoja en lugar de a un rango, este método devuelve 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());
Volver
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
get Range Name()
Obtiene el nombre del rango protegido si está asociado a un rango con nombre. Devuelve null si la protección no está asociada a un rango con nombre. Ten en cuenta que las secuencias de comandos deben llamar de forma explícita a set para asociar un rango protegido con un rango con nombre. Llamar a Range.protect() para crear una protección a partir de un Range que resulte ser un rango con nombre, sin llamar a set, 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. const ss = SpreadsheetApp.getActive(); const range = ss.getRange('A1:B10'); const 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.
Volver
String|null: Es el nombre del rango con nombre protegido o null si el rango protegido no está asociado a 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
get Target Audiences()
Devuelve los IDs de los públicos objetivo que pueden editar el rango protegido.
Volver
Target: 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
get Unprotected Ranges()
Obtiene un array de rangos sin protección dentro de una hoja protegida. Si el objeto Protection corresponde a un rango protegido en lugar de una hoja protegida, este método devuelve un array vacío. Para cambiar los rangos desprotegidos, usa set para establecer un nuevo array de rangos; para volver a proteger toda la hoja, establece un array vacío.
// Unprotect cells E2:F5 in addition to any other unprotected ranges in the // protected sheet. const sheet = SpreadsheetApp.getActiveSheet(); const protection = sheet.protect(); const unprotected = protection.getUnprotectedRanges(); unprotected.push(sheet.getRange('E2:F5')); protection.setUnprotectedRanges(unprotected);
Volver
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
is Warning Only()
Determina si el área protegida usa la protección "basada en advertencias". La protección basada en advertencias significa que todos los usuarios pueden editar datos en el área, excepto que la edición genera una advertencia que le pide al usuario que confirme la edición. De forma predeterminada, los rangos o las hojas protegidos no se basan en advertencias. Para cambiar al estado de advertencia, usa set.
// 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);
Volver
Boolean: true si el rango o la hoja protegidos solo usan la 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()
Quita la protección del rango o la hoja.
// Remove all range protections in the spreadsheet that the user has permission // to edit. const ss = SpreadsheetApp.getActive(); const protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE); for (let i = 0; i < protections.length; i++) { const protection = protections[i]; if (protection.canEdit()) { protection.remove(); } }
// Remove sheet protection from the active sheet, if the user has permission to // edit it. const sheet = SpreadsheetApp.getActiveSheet(); const protection = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0]; if (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
remove Editor(emailAddress)
Quita al usuario indicado 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 podrá editar el área protegida. No se puede quitar al propietario de la hoja de cálculo ni al 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'); // 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
| Nombre | Tipo | Descripción |
|---|---|---|
email | String | Es la dirección de correo electrónico del usuario que se quitará. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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 Editor(user)
Quita al usuario indicado 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 podrá editar el área protegida. No se puede quitar al propietario de la hoja de cálculo ni al 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
| Nombre | Tipo | Descripción |
|---|---|---|
user | User | Es una representación del usuario que se quitará. |
Volver
Protection: El objeto que representa la configuración de protección, para encadenar
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 Editors(emailAddresses)
Quita el array de usuarios determinado 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 podrán editar el área protegida. No se puede quitar al propietario de la hoja de cálculo ni al usuario actual.
// Protect the active sheet, then remove all other users from the list of // editors. const sheet = SpreadsheetApp.getActiveSheet(); const 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. const me = Session.getEffectiveUser(); protection.addEditor(me); protection.removeEditors(protection.getEditors()); if (protection.canDomainEdit()) { protection.setDomainEdit(false); }
Parámetros
| Nombre | Tipo | Descripción |
|---|---|---|
email | String[] | Es un array de direcciones de correo electrónico de los usuarios que se quitarán. |
Volver
Protection: El objeto que representa la configuración de protección, para encadenar
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 Target Audience(audienceId)
Quita el público objetivo especificado como editor del rango protegido.
Parámetros
| Nombre | Tipo | Descripción |
|---|---|---|
audience | String | Es el ID del público objetivo que se quitará. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
set Description(description)
Establece la descripción del rango o la hoja protegidos.
// 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
| Nombre | Tipo | Descripción |
|---|---|---|
description | String | Es la descripción del rango o la hoja protegidos. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
set Domain Edit(editable)
Establece si todos los usuarios del dominio propietario de la hoja de cálculo tienen permiso para editar el rango o la hoja protegidos. Ten en cuenta que los usuarios que tengan permiso de edición explícito podrán editar el área protegida independientemente de este parámetro de configuración. Arroja 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 de gmail.com).
Parámetros
| Nombre | Tipo | Descripción |
|---|---|---|
editable | Boolean | true si todos los usuarios del dominio propietario de la hoja de cálculo deben tener permiso para editar el rango o la hoja protegidos; false si no es así. |
Volver
Protection: El objeto que representa la configuración de protección, para encadenar
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
set Named Range(namedRange)
Asocia el rango protegido con 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 que abarque 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 a partir de un Range que resulte ser un rango con nombre, sin llamar a set, 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
| Nombre | Tipo | Descripción |
|---|---|---|
named | Named | Es el rango con nombre existente que se asociará con el rango protegido. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
set Range(range)
Ajusta el rango que se protege. Si el rango determinado abarca un área diferente del rango protegido actual, este método mueve la protección para que abarque el nuevo rango.
// 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
| Nombre | Tipo | Descripción |
|---|---|---|
range | Range | Es el nuevo rango que se protegerá de las ediciones. |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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
set Range Name(rangeName)
Asocia el rango protegido con 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 que abarque 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 a partir de un Range que resulte ser un rango con nombre, sin llamar a set, 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. const ss = SpreadsheetApp.getActive(); const range = ss.getRange('A1:B10'); const 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
| Nombre | Tipo | Descripción |
|---|---|---|
range | String | Es el nombre del rango con nombre que se protegerá. |
Volver
Protection: El objeto que representa la configuración de protección, para encadenar
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
set Unprotected Ranges(ranges)
Quita la protección del array de rangos determinado dentro de una hoja protegida. Se arroja una excepción si el objeto Protection corresponde a un rango protegido en lugar de una hoja protegida o si alguno de los rangos no está en la hoja protegida. Para cambiar los rangos desprotegidos, establece un nuevo array de rangos; para volver a proteger toda la hoja, establece un array vacío.
// Protect the active sheet except B2:C5, then remove all other users from the // list of editors. const sheet = SpreadsheetApp.getActiveSheet(); const protection = sheet.protect().setDescription('Sample protected sheet'); const 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. const me = Session.getEffectiveUser(); protection.addEditor(me); protection.removeEditors(protection.getEditors()); if (protection.canDomainEdit()) { protection.setDomainEdit(false); }
Parámetros
| Nombre | Tipo | Descripción |
|---|---|---|
ranges | Range[] | Es el array de rangos que se dejarán sin protección dentro de una hoja protegida. |
Volver
Protection: El objeto que representa la configuración de protección, para encadenar
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
set Warning Only(warningOnly)
Establece si este rango protegido usa o no la protección "basada en advertencias". La protección basada en advertencias significa que todos los usuarios pueden editar datos en el área, excepto que la edición genera una advertencia que le pide al usuario que confirme la edición. De forma predeterminada, los rangos o las hojas protegidos no se basan en advertencias. Para verificar el estado de advertencia, usa is.
// 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
| Nombre | Tipo | Descripción |
|---|---|---|
warning | Boolean |
Volver
Protection: Es el objeto que representa la configuración de protección, para encadenar.
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