Importa hiperenlaces a tu hoja de cálculo con la macro de ONLYOFFICE

20 septiembre 2023By Sergey

Los hiperenlaces pueden mejorar enormemente la estética y la funcionalidad de tus hojas de cálculo, facilitando el acceso a recursos cruciales dentro de tus documentos. En esta entrada del blog te mostraremos paso a paso cómo crear una macro que importe hiperenlaces extrayendo los datos de enlace de otra hoja de cálculo.

Importa hiperenlaces a tu hoja de cálculo con la macro de ONLYOFFICE

Creación de la macro

Primero inicializamos dos variables oWorksheetA y oWorksheetB, que representan las hojas de cálculo llamadas Sheet1 y Sheet2 en el documento. También creamos dos matrices vacías titles y links que se utilizarán para almacenar los datos de Sheet1:

var oWorksheetA = Api.GetSheet("Sheet1");
var oWorksheetB = Api.GetSheet("Sheet2");
var rowIndex = 0;
var titles = [];
var links = [];

A continuación, un bucle while itera a través de las filas de Sheet1 (hasta 10 filas en este caso). Dentro del bucle, recupera los valores de las celdas de las columnas A y B, asumiendo que la columna A contiene títulos y la columna B contiene enlaces. Estos valores se almacenan en las matrices titles y links para su uso posterior:

while (rowIndex < 10) {
    var titleCell = oWorksheetA.GetRangeByNumber(rowIndex, 0); // Assuming title is in column A
    var linkCell = oWorksheetA.GetRangeByNumber(rowIndex, 1); // Assuming link is in column B
    var title = titleCell.GetValue();
    var link = linkCell.GetValue();
    titles.push(title); // Store titles in an array
    links.push(link);   // Store links in an array
    rowIndex++; // Increment the row index for the next iteration
}

Luego nos dirigimos al rango seleccionado en Sheet2 (oWorksheetB) e iteramos a través de cada celda en el rango seleccionado usando el método ForEach. Para cada celda, recupera el valor de la celda y comprueba si ese valor coincide con alguno de los títulos almacenados en la matriz titles:

var rangeB = Api.GetSelection();
rangeB.ForEach(function (cell) {
    var cellValue = cell.GetValue();
    // Check if the cell value matches any of the titles from the array
    var index = titles.indexOf(cellValue);
});

Si se encuentra una coincidencia, recupera el título y el enlace correspondientes de las matrices titles y links. También obtiene la dirección de la celda actual en Sheet2 usando cell.GetAddress. Finalmente, establece un hiperenlace en Sheet2 utilizando el título y el enlace recuperados:

if (index !== -1) {
        var title = titles[index];
        var link = links[index];
        var address = cell.GetAddress(true, true, "xlA1", false);
        // Set the hyperlink in oWorksheetB
        oWorksheetB.SetHyperlink(address, link, "Api ONLYOFFICE", title);
    }

La macro completa es la siguiente:

var oWorksheetA = Api.GetSheet("Sheet1");
var oWorksheetB = Api.GetSheet("Sheet2");
var rowIndex = 0;
var titles = [];
var links = [];
while (rowIndex < 10) {
    var titleCell = oWorksheetA.GetRangeByNumber(rowIndex, 0); // Assuming title is in column A
    var linkCell = oWorksheetA.GetRangeByNumber(rowIndex, 1); // Assuming link is in column B
    var title = titleCell.GetValue();
    var link = linkCell.GetValue();
    titles.push(title); // Store titles in an array
    links.push(link);   // Store links in an array
    rowIndex++; // Increment the row index for the next iteration
}
var rangeB = Api.GetSelection();
rangeB.ForEach(function (cell) {
    var cellValue = cell.GetValue();
    // Check if the cell value matches any of the titles from the array
    var index = titles.indexOf(cellValue);
    if (index !== -1) {
        var title = titles[index];
        var link = links[index];
        var address = cell.GetAddress(true, true, "xlA1", false);
        // Set the hyperlink in oWorksheetB
        oWorksheetB.SetHyperlink(address, link, "Your Description", title);
    }
})

Vamos a ejecutar nuestra macro para ver cómo funciona.

Esperamos que esta macro sea una herramienta valiosa para ti. Al utilizar las macros de ONLYOFFICE, podrás mejorar tu productividad y obtener soluciones eficientes y automatizadas.

Mientras te dedicas a la creación de macros, no te pierdas las oportunidades que te ofrece la API de ONLYOFFICE. Si tienes preguntas o ideas innovadoras, te invitamos a compartirlas con nosotros, ya sea a través de comentarios o comunicación directa. Estaremos encantados de recibir tus comentarios y de colaborar contigo. Te deseamos mucha suerte en tus esfuerzos exploratorios.