Utiliza esta macro de ONLYOFFICE para calcular la suma de las celdas resaltadas

14 junio 2024By Sergey

Cuando trabajamos con hojas de cálculo, a menudo hay ocasiones en las que necesitamos calcular la suma de valores específicos. En esta entrada del blog, vamos a detallar el proceso de creación de una macro que calcula la suma de las celdas resaltadas con un color de fondo específico.

Utiliza esta macro de ONLYOFFICE para calcular la suma de las celdas resaltadas

Creación de la macro

  • Accede a la hoja de cálculo activa
    Esta línea obtiene la hoja de cálculo activa en la que se ejecutará la macro:

     const oWorksheet = Api.GetActiveSheet();
  • Establece la celda de referencia y el color
    Para ayudar al editor a identificar el color de destino, primero tenemos que crear una referencia:

        const range1 = oWorksheet.GetRange("B1"); // Set your range for the color reference
        const colorReference = range1.SetFillColor(Api.CreateColorFromRGB(91, 155, 213)); // Set targeted background color
        const targetedColor = range1.GetFillColor();

    Aquí establecemos la celda de referencia (B1) y su color de fondo. El color es RGB (91, 155, 213). Para utilizar colores de la gama existente, añade esta línea:

    const colorReference = range1.SetFillColor(Api.CreateColorFromRGB(91, 155, 213));
  • Define el rango objetivo y la celda de resultado
    Aquí establecemos el rango objetivo de A1 a A16. El resultado se mostrará en la celda A17:

    const range2 = oWorksheet.GetRange("A1:A16"); // Set the targeted range on the spreadsheet
        const result = oWorksheet.GetRange("A17"); // Set the cell where the result will be displayed
  • Establece la variable sum
    Establecemos la variable sum en 0, que contendrá la suma total de los valores:

        let sum = 0;
        let cellColorCode;
  • Itera por cada celda del rango objetivo
    Este bloque itera por cada celda del rango A1, comprueba si el color de fondo de la celda coincide con el color de referencia y, en caso afirmativo, añade el valor de la celda a la suma:

      range2.ForEach(function (range) {
            const cellColor = range.GetFillColor();
           
            if (cellColor!== "No Fill"){
             cellColorCode = cellColor["color"]["ey"]
            } else {
                cellColorCode = null;
            }
            
            if (cellColorCode && cellColorCode === targetedColor["color"]["ey"]) {
                const value = range.GetValue();
                if (!isNaN(parseFloat(value))) {
                    sum += parseFloat(value); 
                }
            }
        });
  • Obtén el resultado
    Por último, establecemos el valor de la celda A17 para que muestre la suma calculada:

    result.SetValue(`The sum: ${sum}`)

El código completo de la macro es el siguiente:

/*About the script:
This script will calculate the sum of the values in the range A1:A16 that have the same background color as the cell B1.
The result will be displayed in the cell A17.
Order of operations:
1) Set the cell for the color reference in the variable 'range1' 
2) Set the targeted fill color in the variable 'colorReference'
3) Set the targeted range in the variable 'range2'
3) Set the cell for dispalying the result in the variable 'result'
4) Before runing the macro, make sure that none of the cells in the range A1:A16 are in the active selection 
*/

(function () {
    const oWorksheet = Api.GetActiveSheet();
    const range1 = oWorksheet.GetRange("B1"); // Set your range for the color reference
    const colorReference = range1.SetFillColor(Api.CreateColorFromRGB(91, 155, 213)); /* Set targeted background color. 
To use colors from the existing range, comment out this line.*/
    const targetedColor = range1.GetFillColor();
    const range2 = oWorksheet.GetRange("A1:A16"); // Set the targeted range on the spreadsheet
    const result = oWorksheet.GetRange("A17"); // Set the cell where the result will be displayed
    let sum = 0;
    let cellColorCode;

    range2.ForEach(function (range) {
        const cellColor = range.GetFillColor();
       
        if (cellColor!== "No Fill"){
         cellColorCode = cellColor["color"]["ey"]
        } else {
            cellColorCode = null;
        }
        
        if (cellColorCode && cellColorCode === targetedColor["color"]["ey"]) {
            const value = range.GetValue();
            if (!isNaN(parseFloat(value))) {
                sum += parseFloat(value); 
            }
        }
    });
    result.SetValue(`The sum: ${sum}`)
})();

¡Vamos a ejecutar nuestra macro y ver cómo funciona!

Esta pequeña macro es una potente forma de automatizar tareas y mejorar tu productividad. Esperamos que se convierta en una adición útil a tu kit de herramientas.

Aprovecha la oportunidad de utilizar el potencial de la API de ONLYOFFICE. Nuestra amplia colección de métodos API puede hacer realidad tus ideas. Tu opinión es muy valiosa. Agradecemos cualquier pregunta o concepto innovador que tengas y esperamos con interés la posibilidad de colaborar. ¡Te deseamos mucha suerte en tus esfuerzos exploratorios!