Todos me ayudaron tanto la última vez que me quedé perplejo que pensé en volver. Aprendí mucho de esa última vez y he tenido éxito en otros proyectos desde entonces.
Estoy trabajando en un script que generará automáticamente una factura en una hoja de cálculo de Google y luego la enviará a PDF. Todo funciona según lo previsto, con la excepción de que si elimino la línea 23 del siguiente código, el nombre del archivo dirá 'Factura 2' pero la factura dirá Factura 1. Solo tenía esa línea allí para intentar rastrear el error, pero funciona según lo previsto con él allí; mi pregunta es ¿por qué se rompe si elimino la línea 23?
¡Gracias de antemano!
function autoInvoice() { // Seting up to handle the spreadsheet var sheetID = 'ID'; //Edit this to your sheet ID. let sheet = SpreadsheetApp.openById(sheetID); let invoice = sheet.getSheetByName('Invoice'); let dataValues = sheet.getSheetByName('Data').getDataRange().getValues(); // Gets all values of the sheet into an array let dataRowNum = sheet.getSheetByName('Data').getLastRow(); // Gets last row of the Autoforward Sheet let invoiceCell = invoice.getRange('C3'); let clientCodeCell = invoice.getRange('C4'); let invoiceDate = invoice.getRange('D5'); // A(0) - Active Client - Yes / No // B(1) - Client Code // C(2) - Client Name // D(3) - Owner Name // E(4) - Owner E-Mail // F(5) - Date of Invoice for (let a = 1; a < dataRowNum; a++) { let clientName = dataValues[a][2]; if (dataValues[a][0] == 'Yes') { clientCodeCell.setValue(dataValues[a][1]); // Changes client code on invoice, sheet code does the rest let invoiceNum = parseInt(invoiceCell.getValue()) + 1; // Adds one to the invoice number invoiceCell.setValue(invoiceNum); // Sets the invoice number on the sheet Logger.log(invoiceNum + " " + invoiceCell.getValue()); // removing this causes the invoice in the file name to be mismatched to the invoice number // Date Conversion var date = new Date(dataValues[a][5]); //convert js date into gs date dataValues[a][5] = Utilities.formatDate(date, "PDT", "yyyy-MM-dd"); //format date using gs method invoiceDate.setValue(dataValues[a][5]); // Sets date on Invoice Utilities.sleep(1000); // Makes PDF const folderName = `Test Folder`; DriveApp.getFoldersByName(folderName) .next() .createFile(SpreadsheetApp.getActiveSpreadsheet() .getBlob() .getAs(`application/pdf`) .setName(dataValues[a][5] + ' - ' + clientName + ' - Invoice #' + invoiceNum)); // Sets file name Logger.log(clientName + ' Active, making Invoice'); Logger.log('Invoice #' + invoiceNum + ' created for ' + clientName); } else { Logger.log(clientName + " no longer active, skipping to next client") } } }Utilities.sleep(1000); para esperar a que finalicen las solicitudes especificadas antes de continuar con la ejecución del código.sleep() aparentemente no es suficiente. El Logger.log le brinda un tiempo de espera adicional para que se obtengan los valores correctos antes de continuar con la ejecución del código.Las operaciones de hoja de cálculo a veces se agrupan para mejorar el rendimiento, como cuando se realizan varias llamadas a Range.getValue(). Sin embargo, a veces es posible que desee asegurarse de que todos los cambios pendientes se realicen de inmediato, por ejemplo, para mostrar los datos de los usuarios mientras se ejecuta un script.
Spreadsheet.flush() se asegurará de que el nombre no se asigne al pdf antes de que se recupere el valor correcto para la iteración de bucle for dada.Spreadsheet.flush() es preferible a Utilities.sleep() dado que obliga a que la operación se sincronice y ajusta automáticamente la cantidad necesaria de "tiempo de inactividad".