📎 Para ordenar todas las columnas por columna de la hoja activa en dos clics mediante un Google Apps Script. El cual crea un menú denominado «🛠️ Tools» y tres submenús. La primera vez solicitara permisos. Después ordena cada columna.
En caso de querer deshacer el ordenamiento. 🖰 Ir a barra de iconos » ⮌ Deshacer ( 🖮 Ctrl + Z )
Submenú «⬇️ A to Z All columns sort ascending» en orden ascendente. Excepto las filas y columnas que estén inmovilizadas.
Submenú «⬆️ Z to A All columns sort descending» en orden descendente. Excepto las filas y columnas que estén inmovilizadas.
Submenú «🔐 Invalidate authorization» Invalida permisos otorgados por los Standalone Scripts. Similar a Google Account: Security Review: Remove access.
💭 Recuerda:
Para ordenar todas las columnas puedes utilizar la opción «Ordenar intervalo por columna»
🖰 » Seleccionar columna » Ir a Menú » ᛨ☰ Ordenar intervalo » Ordenar intervalo por columna.
💡 Propuesta:
📝 Propuesta detalle:
Copiar ( 🖮 Ctrl + V ) código.gs » 🖰 Ir a Menú » Extensiones » Apps Script » Pegar ( 🖮 Ctrl + C ) código.gs » 🖫 Guardar » ⭮ Actualizar hoja de cálculo de Google.
La función «onOpen(e)» es un Simple Triggers se activa al abrir Google Spreadsheet y crea un menú con submenús mediante Class Ui: Method createMenu().
La función «sortColumnAllAscending()» se activa a través del submenú. A su vez esta hace llamada la función genérica «sortColumnAllByColumn()» incluyendo el parámetro «true»
La función «sortColumnAllDescending()» se activa a través del submenú. A su vez esta hace llamada la función genérica «sortColumnAllByColumn()» incluyendo el parámetro «false»
La función «sortColumnAllByColumn(blnAsc)» contiene la Class Range: Method sort() ordena cada columna de la hoja activa Class SpreadsheetApp: Method getActiveSheet() utilizando la variable «booAsc» para ejecutar el orden. pero antes activa la columna. Similar a seleccionar el rango de la columna con Class Range: Method active() de la hoja activa. Excluye las primeras filas por Class Sheet: Method getFrozenRows() y columnas por Class Sheet: Method getFrozenColumns() inmovilizas. Class Sheet: Method setActiveRange() nos posiciona en el rango que anteriormente estábamos con Class Spreadsheet: Method getActiveRange() el cual la hemos almacenado en una variable. Al terminar la ejecución muestra un mensaje temporizado. Parte inferior derecha mediante Class Spreadsheet: Method toast().
La función «invalidateAuthorization» se activa al hacer clic en el submenú «🔐 Invalidate authorization» y retira los permisos ejecutando Class ScriptApp: Method invalidateAuth().
📷 Resultados:
📺 Demo:
💾 Hoja de cálculo de Google:
📚 Referencias:
📎 Para ordenar todas las incluso las ocultas, en dos clics. Mediante un Google Apps Script. El cual crea un menú denominado «🛠️ Tools» y tres submenús. La primera vez solicitara permisos. Después ordena cada columna.
En caso de querer deshacer el ordenamiento. 🖰 Ir a barra de iconos » ⮌ Deshacer ( 🖮 Ctrl + Z )
Submenú «➡️Sheets Sort A to Z» en orden ascendente. Incluso hojas ocultas.
Submenú «⬅️Sheets Sort Z to A» en orden descendente. Incluso hojas ocultas.
Submenú «🔐InvalidateAuthorization» Invalida permisos otorgados por los Standalone Scripts. Similar a Google Account: Security Review: Remove access.
💭 Recuerda:
Para ordenar todas las hojas puedes mover cada pestaña con el cursor.
🖰🠝 » Ir a Menú » 🖿 Hojas ocultas » Mostrar » por cada hoja oculta.
🖰🠝 » Presionar pestaña con el cursor de cada pestaña » ✣ Mover pestaña » Deja de presionar cursor.
💡 Propuesta:
/**
* The event handler triggered when opening the spreadsheet.
* Create menu and submenus.
* @param {event} e The onOpen event.
* @see Trigger onOPen(e):
* https://developers.google.com/apps-script/guides/triggers#onopene
*/
function onOpen(e) {
/* Create menu and submenús. */
SpreadsheetApp.getUi().createMenu('⚒️Tools')
.addItem('➡️Sheets Sort A to Z', 'sortSheetsAscending')
.addItem('⬅️Sheets Sort Z to A', 'sortSheetsDescending')
.addItem('🔐InvalidateAuthorization', 'invalidateAuthorization')
.addToUi();
} /* End onOPen(e) */
/**
* Calling the sortSheets() function.
* Sorts all sheets ascending order.
*/
function sortSheetsAscending() {
sortSheets(true)
} /* End sortSheetsAscending() */
/**
* Calling the sortSheets() function.
* Sorts all sheets descending order.
*/
function sortSheetsDescending() {
sortSheets(false)
} /* End sortSheetsDescending() */
/**
* Function sort all sheets.
* Yes sort sheets hiddens.
* @param {boolean} blnAsc sort ascending true or descendente false.
* Predetermined true.
*/
function sortSheets(blnAsc = true) {
/** Get Class Spreadsheet */
const classSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
/** Get active Class Sheet active */
const getSheetActive = classSpreadsheet.getActiveSheet();
/** Get active range active. */
const getActiveRange = classSpreadsheet.getActiveRange();
/** Get Array class Sheets */
const classSheets = classSpreadsheet.getSheets();
/** Create array all sheet.
* [.][0] sheet name.
* [.][1] statu Hidden.
* [.][2] class sheet.
*/
const sheetNames = classSheets.map(function (classSheet) {
/** text statu hidden */
let statuHidden = classSheet.isSheetHidden();
/* if hidden the show. */
if (statuHidden) { classSheet.showSheet(); }
/* set value array. */
return [classSheet.getSheetName(), statuHidden, classSheet];
});
/* Modify array ascending */
sheetNames.sort();
/* Modify array descending if false parameter. */
if (!blnAsc) { sheetNames.reverse(); }
/* Modify position sheets all ascending or descending. */
sheetNames.forEach(function (sheetName, index) {
/** Get new position sheet. */
let intNewPositionSheet = parseInt(index + 1);
/** if different previous position then move sheet. */
if (sheetName[2].getIndex() !== intNewPositionSheet) {
/* sheet activate. */
sheetName[2].activate();
/* Move sheet orden. */
classSpreadsheet.moveActiveSheet(intNewPositionSheet);
/* Apply all changes. */
SpreadsheetApp.flush();
} /* End if classSheetname.getIndex() !== intNewPositionSheet) */
}); /* End sheetNames.forEach */
/* hidden sheets store */
sheetNames.forEach(function (classSheet) {
/** text statu hidden */
if (classSheet[1]) { classSheet[2].hideSheet(); }
}); /* End sheetNames forEach */
/* Apply all changes */
SpreadsheetApp.flush();
/* Activate sheet previous*/
classSpreadsheet.setActiveSheet(getSheetActive);
/* Activate range previous. */
classSpreadsheet.setActiveRange(getActiveRange);
/* Message in emergent window. Bottom right sample. */
classSpreadsheet.toast('All sheets and sheet hidden', 'Sort')
}/* End sortSheets() */
/**
* Invalidates o valid the authorization.
* @see Method invalidateAuth():
* https://developers.google.com/apps-script/reference/script/script-app#invalidateauth
*/
function invalidateAuthorization() {
ScriptApp.invalidateAuth();
} /* End invalidateAuthorizatio() */
📝 Propuesta detalle:
Copiar ( 🖮 Ctrl + V ) código.gs » 🖰 Ir a Menú » Extensiones » Apps Script » Pegar ( 🖮 Ctrl + C ) código.gs » 🖫 Guardar » ⭮ Actualizar hoja de cálculo de Google.
La función «onOpen(e)» es un Simple Triggers se activa al abrir Google Spreadsheet y crea un menú y submenús mediante Class Ui: Method createMenu().
La función «sortSheetsAscending()» se activa a través del primer submenú. A su vez esta hace una llamada la función genérica «sortSheets()» incluyendo el parámetro «true»
La función «sortSheetsDescending()» se activa a través del segundo submenú. A su vez esta hace una llamada la función genérica «sortSheets()» incluyendo el parámetro «false»
La función «sortSheets(blnAsc)» obtenemos todas las hojas mediante Class Spreadsheet: Method getSheets(). Creamos una matriz que contiene el nombre de cada hoja Class Sheet: Method getSetName(), el valor booleano si la hoja está oculta Class Sheet: Method isSheetHidden(), además si es verdadero la muestra con Class Sheet: Method showSheet() y por finalmente almacenamos la clase de cada hoja Class Sheet: Method getSheets()[]. Después ordena la matriz ascendentemente y si el parámetro «blnAsc» es falso invierte dicha matriz. Ahora si el orden no es el correcto de cada hoja. Activamos la hoja Class Sheet: Method activate() y la desplazamos a su nueva posición con Class Spreadsheet: Method moveActiveSheet(). Recorremos todas las hojas otra vez para ocultar en caso de que en un principio estaban ocultas Class Sheet: Method hiddenSheet(). Recuperamos la hoja activa y rango activo previo Class Spreadsheet: Method setActiveSheet() y Class Spreadsheet: Method setActiveRange(). Al terminar la ejecución muestra un mensaje temporizado. Parte inferior derecha mediante Class Spreadsheet: Method toast().
La función «invalidateAuthorization» se activa al hacer clic en el tercer submenú y retira los permisos. Ejecutando Class ScriptApp: Method invalidateAuth().
📷 Resultado(s):
📺 Demo:
📎 Para mostrar o ocultar las hojas a la vez, en dos clics. Mediante un Google Apps Script. El cual crea un menú denominado «🛠️ Tools» y tres submenús. La primera vez solicitara permisos. Después muestra o oculta las hojas.
En caso de querer deshacer. 🖰 Ir a barra de iconos » ⮌ Deshacer ( 🖮 Ctrl + Z )
Submenú «🗀 Show sheet(s)» muestra las hojas ocultas y almacena los nombres de las hojas.
Submenú «🖿 Hidden sheet(s)» oculta las hojas. Que se han almacenado previamente cuando se activa el submenú mostrar hojas.
Submenú «🔐InvalidateAuthorization» Invalida permisos otorgados por los Standalone Scripts. Similar a Google Account: Security Review: Remove access.
💭 Recuerda:
Para mostrar las hojas ocultas.
🖰 » Ir a Menú » 🖿 Hojas ocultas » Mostrar » por cada hoja oculta.
Para ocultar las hojas.
🖰 » Ir a pestaña » Icono desplegable ⏷ » Ocultar hoja » por cada hoja.
💡 Propuesta:
/*
[Google Spreadsheet Apps Script] 🗀 Mostrar || 🖿 Ocultar. Hojas ocultas a la vez.
https://sites.google.com/view/auba/hoja-calculo-google/apps-script#h.voaxo8za8t7v
*/
/**
* The event handler triggered when opening the spreadsheet.
* Create menu and submenus.
* @param {event} e The onOpen event.
* @link
* https://developers.google.com/apps-script/guides/triggers#onopene
*/
function onOpen(e) {
/** Get Class Ui.
* @link
* https://developers.google.com/apps-script/reference/base/ui
*/
let classUi = SpreadsheetApp.getUi();
/** Get Class Menu.
* @link
* https://developers.google.com/apps-script/reference/base/menu
*/
let classMenu = classUi.createMenu('⚒️Tools');
/* Methods create submenus. */
classMenu.addItem('🗀 Show sheet(s)', 'showSheets');
classMenu.addItem('🖿 Hidden sheet(s)', 'hiddenSheets');
classMenu.addItem('🔐 Invalidate Authorization', 'invalidateAuthorization');
classMenu.addToUi();
} /* End onOPen(e) */
/**
* Calling the sheetsShowHidden() function.
* Show hide sheets.
*/
function showSheets() {
sheetsShowHidden('show')
} /* End showSheets() */
/**
* Calling the sheetsShowHidden() function.
* Hidden sheets shown.
*/
function hiddenSheets() {
sheetsShowHidden('hidden')
} /* End hiddenSheets() */
/**
* Function show or hidden sheets.
* @param {String} [strState='show'] 'show' or 'hidden' the sheets.
* Predetermined 'show.
*/
function sheetsShowHidden(strState = 'show') {
/** Get Class Spreadsheet.
* @link
* https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet
*/
const classSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
/**
* Get Array class Sheets.
* @link
* https://developers.google.com/apps-script/reference/spreadsheet/sheet
*/
const classSheets = classSpreadsheet.getSheets();
/**
* Class Properties.
* @link
* https://developers.google.com/apps-script/reference/properties/properties-service
*/
const classDocumentProperties = PropertiesService.getDocumentProperties();
/** Get name key property. */
const nameKey = 'hiddenSheetStored';
/**
* Reserved variable sheets name.
* @return string or string[]
*/
var getSheetNames;
/*---- Block show ----*/
if (strState === 'show') {
/*
Create array sheets name hide.
return string[].
*/
getSheetNames = classSheets.map(function (classSheet) {
/** Reserved variable sheet name */
let srtSheetName;
/* if hiddenig set the sheet name else void. */
if (classSheet.isSheetHidden()) {
/* set sheet name, yes hide */
srtSheetName = classSheet.getSheetName();
} else {
/* set void, not hide. */
srtSheetName = '';
} /* End if */
return srtSheetName;
}); /* End classSheets.forEach() */
/* Modify array, not value void. */
getSheetNames = getSheetNames.filter(String);
/* exist hidden sheet. Show and store */
if (getSheetNames.length !== 0) {
/* Explore array show sheets. */
classSheets.forEach(function (classSheet) { classSheet.showSheet(); });
/* Transform array to string. */
getSheetNames = getSheetNames.toString();
/* Save store hide sheets name . */
classDocumentProperties.setProperty(nameKey, getSheetNames);
} /* end if getSheetNames.length !== 0 */
} /* End if (strState === 'show') */
/*---- Block hidden ----*/
if (strState === 'hidden') {
/* Get store hide sheets name previous or void. */
getSheetNames = classDocumentProperties.getProperty(nameKey) || '';
/* there are sheets name? */
if (getSheetNames === '') {
/* Transform string to array void. */
getSheetNames = [];
} else {
/* Transform string to array. */
getSheetNames = getSheetNames.split(',');
/* Explore array sheets name. */
getSheetNames.forEach(function (sheetName) {
/** Get class sheet by name.
* @link
* https://developers.google.com/apps-script/reference/spreadsheet/sheet
*/
let classSheetName = classSpreadsheet.getSheetByName(sheetName);
/* If not exit sheet break */
if(!classSheetName){return;};
/* if name sheet exist then hidden. */
if (classSheetName) { classSheetName.hideSheet(); }
}); /* End forEach() */
/* Delete store hide sheets name . */
classDocumentProperties.setProperty(nameKey, '');
}
} /* End strState === 'hidden' */
/* Message in emergent window. Bottom right sample. */
classSpreadsheet.toast(getSheetNames.length === 0 ? 'There is not' : getSheetNames, `Sheet(s) ${strState}`)
}/* End sheetsShowHidden() */
/**
* Invalidates the authorization.
* @link
* https://developers.google.com/apps-script/reference/script/script-app#invalidateauth
*/
function invalidateAuthorization() {
ScriptApp.invalidateAuth();
} /* End invalidateAuthorizatio() */
📝 Propuesta detalle:
Copiar ( 🖮 Ctrl + V ) código.gs » 🖰 Ir a Menú » Extensiones » Apps Script » Pegar ( 🖮 Ctrl + C ) código.gs » 🖫 Guardar » ⭮ Actualizar hoja de cálculo de Google.
La función «onOpen(e)» es un Simple Triggers se activa al abrir Google Spreadsheet y crea un menú y tres submenús mediante Class Ui: Method createMenu().
La función «showSheets()» se activa a través del primer submenú. A su vez esta hace una llamada la función genérica «sheetsShowHidden()» incluyendo el parámetro «'show'»
La función «hiddenSheets()» se activa a través del segundo submenú. A su vez esta hace una llamada la función genérica «sheetsShowHidden()» incluyendo el parámetro «'hidden'»
La función «sheetsShowHidden(strState)» obtenemos todas las hojas mediante Class Spreadsheet: Method getSheets(). Obtenemos las propiedades de almacén Class Properties: Method getDocumentProperties(). Si el parámetro «strState» es igual a «'show'» entonces guardamos en un variable matriz «getSheetNames» memorizamos los nombres de las hojas ocultas. Después mostramos las hojas con Class Sheet: Method showSheet(). la variable matriz la convertimos en cadena y la almacenamos con un nombre clave en Class Properties: Method setProperty(). Si el parámetro «strState» es igual a «hidden'» recuperamos los nombres de las hojas almacenadas con el nombre clave mediante Class Properties: Method getProperties() en caso de no haber retorna cadena vacía. Está variable de cadena la convertimos en matriz. Adquirimos la clase de cada hoja por su nombre Class Spreadsheet: Method getSheetByName(). Si existe la hoja entonces la ocultamos Class Sheet: Method hiddenSheet(). Al terminar la ejecución muestra un mensaje temporizado. Parte inferior derecha mediante Class Spreadsheet: Method toast().
La función «invalidateAuthorization» se activa al hacer clic en el tercer submenú y retira los permisos. Ejecutando Class ScriptApp: Method invalidateAuth().
📷 Resultado(s):
📺 Demo:
💾 Hoja de cálculo de Google:
🗪 Para operar con múltiples intervalos con valores numéricos estáticos. En este ejemplo aumentar o disminuir el valor por una operación aritmética de porcentaje. Mediante un Google Apps Script. El cual crea un menú denominado «🛠️ Tools» y dos submenús. La primera vez solicitara permisos. Después pregunta el porcentaje a valorar.
En caso de querer deshacer. 🖰 Ir a barra de iconos » ⮌ Deshacer ( 🖮 Ctrl + Z )
Submenú «Operate %» muestra cuadro de entrega para escribir el porcentaje.
Submenú «🔐Invalidate authorization» Invalida permisos otorgados por los Standalone Scripts. Similar a Google Account: Security Review: Remove access.
💭 Recuerda:
Para seleccionar múltiples intervalos mantén pulsada la tecla control y elige los intervalos con el ratón.
🖮 (🗦🖰, Ctrl +🗦🖰)
💡 Propuesta:
/**
* @OnlyCurrentDoc
* @see {@link https://developers.google.com/apps-script/guides/services/authorization?hl=419} Information.
*/
/**
* The event handler triggered when opening the spreadsheet.
* Function show menu.
* @param {Event} e The onOpen event.
*/
function onOpen(e) {
/** Get class SpreadsheetApp */
const classUi = SpreadsheetApp.getUi();
/* Create a menu and two submenu. */
classUi.createMenu('🛠️ Tools')
.addItem('Operate %', 'promptPercenten')
.addItem('🔐 Invalidate authorization', 'invalidateAuthorization')
.addToUi();
} /* End function onOPen */
/**
* Invalidates the authorization.
* @see Method invalidateAuth():
* https://developers.google.com/apps-script/reference/script/script-app#invalidateauth
*/
function invalidateAuthorization() {
/* Invalidate authorization */
ScriptApp.invalidateAuth();
} /* End invalidateAuthorizatio() */
/**
* set values active range list operate percenten.
* @param {float} floatPercenten number operate percenten.
*/
function operatePercentenRangeList(floatPercenten) {
/** Get the class of the active spreadsheet */
const classSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
/** Get the class of the active sheet. */
const classSheet = classSpreadsheet.getActiveSheet();
/** Get array class of the active range list. */
const classRangeList = classSheet.getActiveRangeList().getRanges();
/** Get array A1Notation active range list. */
const arrA1Notation = classRangeList.map(function (classRange) { return classRange.getA1Notation(); });
/* Loop array string A1Notation */
arrA1Notation.forEach(function (strA1Notation) {
/** New array range values */
const arrValues = classSheet.getRange(strA1Notation).getValues();
/* Loop row range each values */
arrValues.forEach(function (rowValue, rowIndex) {
/* /* Loop column range each value */
rowValue.forEach(function (columnValue, columnIndex) {
/* is number? */
if (columnValue < 0 || columnValue > 0) {
/** convert number */
let valueFloat = parseFloat(columnValue);
/* Operate percenten */
arrValues[rowIndex][columnIndex] = [valueFloat + valueFloat / 100 * floatPercenten];
}; /* End if(columnValue) */
});/* End forEach(rowvalue) */
}); /* End forEach(arrValues) */
/* set values each range */
classSheet.getRange(strA1Notation).setValues(arrValues);
}); /* End forEach() */
} /* End operatePercentenRangeList() */
/**
* show input box
* @param {string} msg message.
*/
function promptPercenten(msg = '') {
/** Get class SpreadsheetApp */
const classUi = SpreadsheetApp.getUi();
/** set response dialog */
const setResponse = classUi.prompt('Enter percenten not write %', msg, classUi.ButtonSet.OK_CANCEL);
/* is response OK? */
if (setResponse.getSelectedButton() === classUi.Button.OK) {
/** get response write */
const getResponse = setResponse.getResponseText();
/* is number? */
if (getResponse < 0 || getResponse > 0) {
/** call function operate percenten y return value convert number */
operatePercentenRangeList(parseFloat(getResponse));
} else {
/* call function again not number */
promptPercenten('Not number ' + getResponse);
} /* End if(getResponse) */
} /* End if(setResponse) */
} /* End promptPercenten() */
📝 Propuesta detalle:
Copiar ( 🖮 Ctrl + V ) código.gs » 🖰 Ir a Menú » Extensiones » Apps Script » Pegar ( 🖮 Ctrl + C ) código.gs » 🖫 Guardar » ⭮ Actualizar hoja de cálculo de Google.
La función «onOpen(e)» es un Simple Triggers se activa al abrir Google Spreadsheet y crea un menú y submenús mediante Class Ui: Method createMenu().
La función «promptPercenten(msg)» se activa a través del primer submenú. Muestra un cuadro de entrada para escribir el valor numérico en positivo o negativo mediante Class Ui: Method prompt() si el valor no es numérico vuelve a preguntar. A su vez esta hace una llamada la función «operatePercentenRangeList(floatPercenten)» incluyendo el parámetro «number»
La función «operatePercentenRangeList(floatPercenten)» obtenemos hoja activa Class SpreadsheetApp: Method getActiveSheet() y sus intervalos seleccionados con Class Sheet: Method getActiveRangeList(). Creamos una matriz que contiene el nombre tipo anotación Class Range: getA1Notation() para después establecer el nuevo valor.
La función «invalidateAuthorization» se activa al hacer clic en el segundo submenú y retira los permisos. Ejecutando Class ScriptApp: Method invalidateAuth().
📷 Resultado(s):
📺 Demo:
💾 Hoja de cálculo de Google:
🗪 Para que se sitúe automáticamente a la última celda editada. Al abrir la hoja de cálculo. He formado un código de Google Apps Script.
🎩 𝐓𝐫𝐢𝐜𝐤(𝐬):
Puedes llamar manualmente a la función:
goLastCellEdited(true); ó goLastCellEdited(false);
se requiere autorización.
💭 𝐑𝐞𝐦𝐞𝐧𝐛𝐞𝐫:
Este código no requiere autorización para otorgar permisos.
💡𝐏𝐫𝐨𝐩𝐨𝐬𝐚𝐥(𝐬):
📝 𝐏𝐫𝐨𝐩𝐨𝐬𝐚𝐥(𝐬) 𝐝𝐞𝐭𝐚𝐢𝐥(𝐬):
La función «goLastCellEdited(isGoLast,e)» está insertada en Simple Triggers. El primero es onOpen(e) Se activa al abrir la hoja de cálculo. La cual activa la función que se encargará de mover a la última celda editada.. El segundo onEdit(e) se activa al editar la celda cuando insertamos un valor nuevo, diferente al anterior o borramos el valor. Esta activa la función para registrar el nombre de la hoja y el rango editado.
«goLastCellEdited(isGoLast,e)» La variable «e» de tipo Event Object utilizamos sus propiedades (parámetro opcional). Variable «isGolast» parámetro obligatorio. Sólo Admite dos valores al ser booleano.
«if (typeof isGoLast !== "boolean")» La variable comprueba los dos estado verdadero o falso. En caso contrario fin de ejecución.
«const classUserProperties = PropertiesService.getUserProperties()» Obtenemos la Class PropertiesService para utilizar sus métodos y guardar o recuperar los valores para localizar la celda editada. El Class Properties Method getUserProperties() Se refiere al usuario actual.
«const key = 'getCurrentCell'» Asignamos Variable a la clave para recuperar o guardar los valores.
«if(isGoLast === false)» Si la variable es falsa se ejecuta la opción de guardar los valores.
«const classCell = e?.range || SpreadsheetApp.getActiveSpreadsheet().getActiveRange()» Obtenemos la Class Range mediante la variable tipo objecto o Class Spreadsheet.
«const setValuesKeyObject = {
activeSheetName: classCell.getSheet().getSheetName(),
rowStart: e?.range?.rowStart || classCell.getRow(),
columnStart: e?.range?.columnStart || classCell.getColumnRow()
}»
Creamos una variable tipo objecto donde:
«activeSheetName» Establecemos el nombre de la hoja a través del rango por mediación de Class Range Method getSheet()
«rowStart» Establecemos el número de inicio de fila editada, obtenida por el objeto. Si es nulo o cero se obtendrá por la Class Range Method getRow()
«columnStart» Establecemos el número de inicio de columna editada, obtenida por el objeto. Si es nulo o cero se obtendrá por la Class Range Method getColumn()
«classUserProperties.setProperty(key, JSON.stringify(setValuesKeyObject))» Convertimos la variable tipo objeto en variable tipo cadena utiliando el metodo JSON.stringify() y guardamos en los servidores de Google con Class Properties Method setProperty()
«if(isGoLast === true)» Si la variable es verdadera ejecuta la opción de recuperar los valores y activar la última celda editada.
«const getValuesKeyString = classUserProperties.getProperty(key)» Recuperar el valor almacenado mediante Class Properties Method setProperty()
«if(!getValuesKeyString)» Si el valor recuperado es nulo. Fin de ejecución.
«let getValuesKeyObject = JSON.parse(getValuesKeyString)» Establecemos en una variable el valor recuperado y convertir de cadena a objeto con JSON.parse()
«const objectSource = e?.source» Variable para establecer origen mediante objecto.
«const classSpreadsheet = objectSource || SpreadsheetApp.getActiveSpreadsheet()» Variable para obtener la Class Spreadsheet mediante objeto o llamando a la Class SpreadsheetApp Method getActiveSpreadsheete()
«const classSheet = classSpreadsheet.getSheetByName(getValuesKeyObject.activeSheetName)» Obtenemos la Class Sheet mediante el nombre de la hoja utilizando Class Spreadsheet Method getSheetByName()
«if(classSheet)» Si no es nulo la variable entonces existe la hoja y continua la función.
«classSheet.activate()» Activamos la hoja aunque esté oculta y se visualiza. LLamada a Class Sheet Method activate()
«if(classSheetMaxRows < getValuesKeyObject.rowStart)» Comprobamos que la fila editada exista.
«getValuesKeyObject.rowStart = classSheetMaxRows» Si no existe la fila editada establecemos la última fila.
«if(classSheetMaxColumns < getValuesKeyObject.columnStart)» Comprobamos que exista la columna editada.
«getValuesKeyObject.columnStart = classSheetMaxColumns» Si no existe la columna editada establecemos la última columna.
«if(getValuesKeyObject.rowStart > 1 && getValuesKeyObject.columnStart > 1)» Comprobamos que sea la fila y columna número uno.
«classSheet.getRange(getValuesKeyObject.rowStart, getValuesKeyObject.columnStart).activate();» Activamos la celda editada para que el cursor se dirija.
«Logger.log(messageLog)» Enviamos la información acumulada en el proceso con el parámetro Addition assignment (+=) y Class Logger
«return messageLog» fin de la ejecución retornado mensaje tipo cadena.
«/** */» Sistema de comentarios. Etiquetas tipo JSDoc
💡𝐏𝐫𝐨𝐩𝐨𝐬𝐚𝐥(𝐬) 𝐫𝐞𝐝𝐮𝐜𝐞𝐝 𝐯𝐞𝐫𝐬𝐢𝐨𝐧:
📷 𝐑𝐞𝐬𝐮𝐥𝐭(𝐬):
📺𝐃𝐞𝐦𝐨𝐧𝐬𝐭𝐫𝐚𝐭𝐢𝐨𝐧(𝐬):
💾 𝐆𝐨𝐨𝐠𝐥𝐞 𝐒𝐩𝐫𝐞𝐚𝐝𝐬𝐡𝐞𝐞𝐭(𝐬):
🌍 𝐆𝐨𝐨𝐠𝐥𝐞 𝐒𝐢𝐭𝐞(𝐬):
📚 𝐑𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞(𝐬)
🗪 Para retiriar persimos otorgados de forma automática después de una inactividad de 30 días. Propongo un código de Google Apps Script.
🎩 𝐓𝐫𝐢𝐜𝐤(𝐬):
Inserta la función después del código que necesite permisos para mayor efectividad. Evitando introducirla en onOpen(e)
💭 𝐑𝐞𝐦𝐞𝐧𝐛𝐞𝐫:
Puedes crear un menú.
🔬 𝗜𝗻𝘃𝗲𝘀𝘁𝗶𝗴𝗮𝘁𝗲:
¿Qué ocurre si necesitamos retirar permisos para una inactividad de menos de un día?
inactivityPermits(false, 0.5);
💡𝐏𝐫𝐨𝐩𝐨𝐬𝐚𝐥(𝐬):
📝 𝐏𝐫𝐨𝐩𝐨𝐬𝐚𝐥(𝐬) 𝐝𝐞𝐭𝐚𝐢𝐥(𝐬):
«/** @OnlyCurrentDoc */» Sistema de seguridad solo interactúa con Google Spreadsheet actual. Authorization for Google Services
«'use strict';» Seguridad en el código al programar. Strict mode
«/** */» Genera documentación para las funciones y variables. Tipo JSDoc
«function inactivityPermits(isNow = true, expirationDays = 30)» Parametros de la función con sun valores por defecto.
«isNow = true» Retira los permisos inmediatamente.
«isNow = false» Retira los permisos basado en el tiempo.
«expirationDays = 30» Días trascurrido para retirar permisos si no hay actividad.
«if(typeof isNow !== 'boolean') isNow = true» Comprueba que el parámetro sea de tipo booleano. En caso contrario establece valor verdadero.
«expirationDays = Number(expirationDays);
if(!(expirationDays > 0)) expirationDays = 30» Comprueba que el parámetro sea de tipo numérico. En caso contrario establece valor de treinta días.
«const HANDLER_FUNCTION_NAME = 'inactivityPermits'» Variable constante del nombre de la función.
«const KEY_NAME = 'trigger'» Variable constante del nombre de la clave para guardar o recuperar la fecha de ejecución la retirada de permisos.
«const MS_PER_DAY = 86400000» Variable constante que establece la equivalencia en milisegundos de un día:
1(dd) * 24(hh) * 60(mm) * 60(ss) * 1000(ms)
«const classScriptProperties = PropertiesService.getScriptProperties()» Variable constante para obtener la clase y métodos de Class Properties Method getScriptProperties()
«const currentDate = new Date()» Estable la fecha y hora actual. Según zona horaria establecida:
🖰 » Barra lateral menú » ⚙️ Configuración del proyecto
«function inactivityPermitsManual()» Función integrada en la función principal para retirar los permisos.
«ScriptApp.invalidateAuth()» Class ScriptApp Method invalidateAuth() para invalidar permisos similar si acedemos a Google Account: Security Review: Remove access.
«function deleteTriggers()» Función integrada en la función principal para eliminar Installable triggers.
«ScriptApp.getProjectTriggers()
.forEach(
function(classTrigger){
try{
if(classTrigger.getHandlerFunction() === HANDLER_FUNCTION_NAME){
ScriptApp.deleteTrigger(classTrigger);
}» La Class ScriptApp Method getProjectTriggers() obtenemos todos los Installable triggers metodo forEach() recorre cada uno de ellos.
cuando la función del controlador Class trigger Method getHandlerFunction() coincide con el nombre la función, entonces eliminar Class ScriptApp Method deleteTrigger().
«function newTrigger()» Funcion integrada en la función principal para crear un Installable trigger.
«const expirationMillisecond = expirationDays * MS_PER_DAY» obtenemos los días en milisegundos.
«const expirationDate = new Date(currentDate.getTime() + expirationMillisecond)» calculamos la diferencia sobre la fecha actual.
«ScriptApp.newTrigger(HANDLER_FUNCTION_NAME)
.timeBased()
.at(expirationDate)
.create();» Creamos un activador basado en el tiempo mediante Class ScripApp Method newTrigger().
Tipo Class ClockTriggerBuilder.
«classScriptProperties.setProperty(KEY_NAME,expirationDate)» Almacenamos la fecha en una base datos de Google utilizando Class Properties Method setProperty()
«if (isNow === true)» si es verdadero eliminar permisos inmediatamente.
«else{» Si no es verdadero....
«const valueKey = classScriptProperties.getProperty(KEY_NAME)» Recuperamos la fecha/hora con Class Properties Method getProperty().
«if(valueKey)» Si no hay valor al recuperarlo....
«const differenceDays =(new Date(valueKey).getTime() - currentDate.getTime()) / MS_PER_DAY» Variables constante para cálcular.
Diferencia en días de la fecha/hora de ejcucion por inactividad y fecha/hora actual.
«if(differenceDays <= 0)» Valor negativo ejecutar retirar permisos.
«}else if(differenceDays <= (expirationDays / 2))» Si a transcurrido el 50% del tiempo renovar activador.
«}else{» Si hay valor almacenado crear activador.
📷 𝐑𝐞𝐬𝐮𝐥𝐭(𝐬):
📺𝐃𝐞𝐦𝐨𝐧𝐬𝐭𝐫𝐚𝐭𝐢𝐨𝐧(𝐬):
💾 𝐆𝐨𝐨𝐠𝐥𝐞 𝐒𝐩𝐫𝐞𝐚𝐝𝐬𝐡𝐞𝐞𝐭(𝐬):
📚 𝐑𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞(𝐬):