Google Script: Could not find range to get data from Spreadsheet - google-apps-script

I am trying to get email via google app script. What I am doing is I get an alert email if a person's birthday is today. I have an google sheets which already have those data. But I am having a problem in few things. First, below is my code which I am running
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var birthdaysSheet = activeSheet.getSheetByName("Data");
var settingsSheet = activeSheet.getSheetByName("Settings");
var sendEmailTo = settingsSheet.getRange("B4").getValue();
function emailAlert() {
if (turnOnEmailNotice.toLowerCase() == "no")
{
Logger.log("The Email Notification is NOT turned ON. System will Exit.");
exit
}
//Get the total number of filled row in the sheet.
var currentRowAT = 2;
var currentCellValueAT = "start";
while (currentCellValueAT != ""){
if (currentCellValueAT = birthdaysSheet.getRange("A" + currentRowAT).getValue() != ""){
currentRowAT = currentRowAT +1;
}
}
var birthdaysSheetLastRow = currentRowAT - 1;
// Get today's Date (with Month, Date and Year)
var today = new Date();
var todayMth = today.getMonth()+1;
var todayDate = today.getDate();
var todayYear = today.getFullYear();
for (k=2; k < birthdaysSheetLastRow + 1; k++)
{
var targetBday = new Date();
targetBday = birthdaysSheet.getRange("P" + k).getValue();
// If Birthday is not speicified, continue with the next row
if (targetBday == ""){continue};
var unadjTargetBday = new Date();
var unadjTargetBdayMth = targetBday.getMonth()+1;
var unadjTargetBdayDate = targetBday.getDate();
var unadjTargetBdayYear = targetBday.getFullYear();
var unadjTargetBday = targetBday;
targetBday.setDate(targetBday.getDate()-daysInAdvance); // Calculating how many days in advance you want to trigger the notification. This is set in Settings Tab.
var targetBdayMth = targetBday.getMonth()+1;
var targetBdayDate = targetBday.getDate();
if (targetBdayMth + " " + targetBdayDate == todayMth + " " + todayDate)
{
var targetBirthDateYearsOld = (today.getYear() - unadjTargetBday.getYear())-1900;
prepareAndSendEmail(k, targetBirthDateYearsOld);
}
}
}
/*
* This method actually prepares the HTML of the email body and send it out.
*/
function prepareAndSendEmail(row, targetBirthDateYearsOld)
{
var firstName= birthdaysSheet.getRange("A" + row).getValue();
var lastName = birthdaysSheet.getRange("B" + row).getValue();
var emailAddress = birthdaysSheet.getRange("D" + row).getValue();
var Birthday = birthdaysSheet.getRange("C" + row).getValue();
var message = "";
message = message + "Hi all," + NEW_LINE + NEW_LINE;
message = message + "Today is <B style=\"color:tomato\">" + firstName + " " + lastName + "</B>'s Birthday." + NEW_LINE + NEW_LINE;
var tableHeader = "";
tableHeader = tableHeader + "<table width=\"40%\" style=\"background-color:#FF8040;align:center;font-family:calibri,arial\" border=\"0\" cellpadding=\"2\" cellspacing=\"0\" >";
tableHeader = tableHeader + "<tr style=\"text-align:center;font-weight: bold;height:5px;\"> <td> </td> <td></td></tr>";
message = message + tableHeader;
var color = "GhostWhite";
message = message + "<TR style=\"background-color:" + color + "\"> <TD style=\"text-align:left;font-weight: bold;\"> Birthday: </TD> <TD>" + formatDate(targetCandidateBirthday) + "</TD>";
message = message + "<TR style=\"background-color:" + color + "\"> <TD style=\"text-align:left;font-weight: bold;\"> Age: </TD> <TD>" + targetBirthDateYearsOld + "</TD>";
message = message + "<TR style=\"background-color:" + color + "\"> <TD style=\"text-align:left;font-weight: bold;\"> Email: </TD> <TD>" + targetCandidateEmailAddress + "</TD>";
}
Question:
What I am making mistake as I am having error getting range at var firstName= birthdaysSheet.getRange("A" + row).getValue();
--Error: Range not found
I think my code to get age is also seems to be wrong.
If I am using only first row then age is coming as undefined.

I'm wondering if your first loop would be better if structured like this:
//Get the total number of filled row in the sheet.
var currentRowAT = 2;
var currentCellValueAT = "start";
var thisRow, theBirthday = "";
var birthdayData = birthdaysSheet.getRange(1, 1, birthdaysSheet.getLastRow()); //Get all of column A data
for (var i=0;i<birthdayData.length;i+=1) {
thisRow = birthdayData[i];
theBirthday = thisRow[0];
if (theBirthday === "") {
var birthdaysSheetLastRow = currentRowAT - 1;
break; //Stop looping through the data
};
};

Problem was solved. I just ran the script in excel sheet. It worked. Didn't changed anything.
Thank You Guys for your help.

Related

Very slow scripts (with weird errors) after a recovery of a previous version of a spreadsheet

I was having problems with a spreadsheet, and I decided to go back to a previous version...
However, I noticed that after this restoration, the spreadsheet SCRIPTS were SUPER SLOW (often shutting down by timeout) and presenting errors that I've never seen! (like the ones I posted above). It's like the script is having a hard time finding the spreadsheet...
Does anyone know how I can resolve this? I've tried everything!
Look at this simple script, which starts quickly, but on the first line it takes 2 MINUTES to perform!!! (Full script after screenshot)
Script:
function atualizarDisparos() {
Logger.log("step1")
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('DB');
Logger.log("step2")
var startRow = 27; // Lembrar de tirar o cabeƧalho
var quantidadeDeViveiros = 16;
var lastRow = startRow + quantidadeDeViveiros; // figure out what the last row is
Logger.log("step4")
var startColumn = 2; // Lembrar de tirar as bordas
var lastColumn = ss.getLastColumn(); // figure out what the last column is
var numColumns = lastColumn-startColumn+1; // subtrair um pelo outro
var dataRange = ss.getRange(startRow, startColumn, quantidadeDeViveiros, numColumns)
var data = dataRange.getValues();
var povoamento ="";
var bioensaio ="";
var despesca ="";
var povoadoHoje ="";
var atualizar = 0;
var biomassaDespesca = 2000;
var tamanhoDespesca = 18;
var tempoBioensaio = 3;
var diasParaVenda = 15;
Logger.log("step4")
for (var linhaAtual = 0; linhaAtual <= quantidadeDeViveiros-1; linhaAtual++) {
var row = data[linhaAtual];
Logger.log("step5")
if (row[7] == 0 || row[35] < diasParaVenda) { //==== POVOAMENTO
var povoamento = povoamento + "V" + row[0] + " (" + row[12] + "kg de " + row[14] + "g) || "
var atualizar = 1;
}
if (row[7] != 0 && row[9] == "" && row[11] <= 3) { //=== BIOENSAIO
var dataPovoamento = new Date(row[5]);
var dataBioensaio = dataPovoamento.setDate(dataPovoamento.getDate()+tempoBioensaio-1);
var dataBioensaio = new Date(dataBioensaio);
var dataHoje = new Date();
Logger.log(dataBioensaio)
Logger.log(dataHoje)
if (dataHoje >= dataBioensaio) {
var dataBioensaio = Utilities.formatDate(dataBioensaio, Session.getScriptTimeZone(), 'dd/MM/yy');
var bioensaio = bioensaio + "V" + row[0] + " (Tirar Bioensaio: " + dataBioensaio + ") || "
}
var atualizar = 1;
}
if (row[7] != 0 && row[8] == 0) { //=== POVOADO HOJE
var dataPovoamento = new Date(row[5]);
var dataPovoamento = new Date(dataPovoamento);
var dataPovoamento = Utilities.formatDate(dataPovoamento, Session.getScriptTimeZone(), 'dd/MM/yy');
var povoadoHoje = povoadoHoje + "V" + row[0] + " (Povoado dia: " + dataPovoamento + ") || "
var atualizar = 1;
}
if (row[14] >= 8 && row[35] < diasParaVenda) { //=== DESPESCA
var despesca = despesca + "V" + row[0] + " (" + row[12] + "kg de " + row[14] + "g) || "
var atualizar = 1
}
}
if(atualizar == 1) {
var ssPC = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PC');
ssPC.getRange('k107').setValue(povoamento);
ssPC.getRange('k108').setValue(bioensaio);
ssPC.getRange('k109').setValue(despesca);
ssPC.getRange('k123').setValue(povoadoHoje);
}
}

Resolve 'Parsing Error: Please check your selector. (line XX)' Javascript/AWQL AdWords Data Grabber

Let me start by saying I am not a developer, so please forgive my ignorance here. :)
For the attached script, I am receiving the error: Parsing error. Please check your selector. (line 103)
For the life of me, I can't figure out how to fix this and I've done an extensive online search.
For reference, here is where the script came from: https://searchengineland.com/script-automates-adding-adwords-data-google-spreadsheet-277724
Any solutions would be much appreciated!
(Note that the personal info in the lines 17-21 have been filled out correctly.)
Thanks,
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "exa...#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}

Google Apps Script | How to access Row/Column data for certain ranges

I'm brand new to Google app scripts and wanted to create an automation script for data I am collecting through a google form.
I have 3 fields that users fill out in a form that populate columns in a sheet.
Google Sheet Image
From the responses, I want to automatically generate a database entry for another scripting language "Papyrus" by simply writing out the code as a modified concatenated string.
ex.
GasMaskM1A211.PluginFile = Context.Plugin
GasMaskM1A211.FormID = 0x00007A77
GasMaskM1A211.TypeClass = ClassGasMask
Add(GasMaskM1A211)
I'm not quite sure how to go about accessing the data (Strings) from the columns and writing to a separate column that will have the concatenated string.
So far, I've tried to follow a few examples online that did similar but not quite what I was trying to accomplish and this was the result.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var lastRow = range.getLastRow();
function onOpen(e) {
getValues();
}
function getValues() {
var sortColumnRange = sheet.getRange("B2:D100");
var sortColumnVals = sortColumnRange.getValues();
var cell;
for(var i = 1; i < sortColumnVals.length; i++){
if(sortColumnVals[i][0] !== ""){
var armorName = sortColumnVals[i][3].toString()
var formID = sortColumnVals[i][2].toString()
var pluginName = sortColumnVals[i][1].toString();
pluginName.replace(" ","_");
pluginName.replace(".esp","_ESP");
pluginName.replace(".esm","_ESM");
var entry = "string " + pluginName + " = " + sortColumnVals[i][0].toString() + "\n";
entry = entry + "Entry " + armorName + " = New Entry \n";
entry = entry + armorName + ".PluginFile = " + pluginName + "\n";
entry = entry + armorName + ".FormID = " + formID + "\n";
entry = entry + armorName + ".TypeClass = ClassGasMask \n";
entry = entry + "Add(" + armorName + ")";
Logger.log(entry);
cell = sheet.getRange(i, 5);
cell.setValue(entry);
}
}
}
There are no apparent error messages, but I get the feeling that I am not accessing the right cells. Nothing gets printed to the log nor entered into the sheet.
There is a problem with your array indexes. In Javascript (and thus Google Script), array indexes start at 0. So you should decrease all your index numbers with 1, and I believe it will work (at least, when quickly tested, it does return something, although I can't assess whether that's what you'd expect or not).
function getValues() {
var sortColumnRange = sheet.getRange("B2:D100");
var sortColumnVals = sortColumnRange.getValues();
var cell;
for(var i = 0; i < sortColumnVals.length; i++){
if(sortColumnVals[i][0] !== ""){
var armorName = sortColumnVals[i][2].toString()
var formID = sortColumnVals[i][1].toString()
var pluginName = sortColumnVals[i][0].toString();
pluginName.replace(" ","_");
pluginName.replace(".esp","_ESP");
pluginName.replace(".esm","_ESM");
var entry = "string " + pluginName + " = " + sortColumnVals[i][0].toString() + "\n";
entry = entry + "Entry " + armorName + " = New Entry \n";
entry = entry + armorName + ".PluginFile = " + pluginName + "\n";
entry = entry + armorName + ".FormID = " + formID + "\n";
entry = entry + armorName + ".TypeClass = ClassGasMask \n";
entry = entry + "Add(" + armorName + ")";
Logger.log(entry);
cell = sheet.getRange(i, 5);
cell.setValue(entry);
}
}
}

Google app script triggering twice after Google form submit

I'm having issue with my script running twice in a Google Form and the linked Sheets. I have one form submit trigger. If I delete this trigger, the script doesn't run at all on a form submit. If I add the trigger back in, it will trigger twice -- but there is only one form submittal in the sheet responses. I thought that maybe I was clicking the form submittal twice, but that doesn't seem to be it. Thanks.
Here is the code:
function myFunction(e) {
// Set values for event "e" from Response form, each number being a column in the spreadsheet. Column zero is not used - it is the timestamp
var JobNumber = e.values[1];
// Create an array from the PNEZD field in the form then find the array location for the inputted shot number
var PNEZD_field = e.values[2];
var PNEZD_array = Utilities.parseCsv(PNEZD_field);
var StructureNumber = e.values[3];
for (i = 0; i < PNEZD_array.length; i++) {
if (PNEZD_array[i][0] == StructureNumber) {
var Elevation = PNEZD_array[i][3];
var Easting = PNEZD_array[i][2];
var Northing = PNEZD_array[i][1];
}
}
// STRUCTURE TYPE AND SIZE
var StructureType = e.values[4];
var StructureSize = e.values[5];
// PIPE NUMBER 1
var PipeSize1 = e.values[6];
var PipeMaterial1 = e.values[7];
var PipeDirection1 = e.values[8];
var PipeMeasureDown1 = e.values[9];
// PIPE NUMBER 2
var PipeSize2 = e.values[10];
var PipeMaterial2 = e.values[11];
var PipeDirection2 = e.values[12];
var PipeMeasureDown2 = e.values[13];
// PIPE NUMBER 3
var PipeSize3 = e.values[14];
var PipeMaterial3 = e.values[15];
var PipeDirection3 = e.values[16];
var PipeMeasureDown3 = e.values[17];
// PIPE NUMBER 4
var PipeSize4 = e.values[18];
var PipeMaterial4 = e.values[19];
var PipeDirection4 = e.values[20];
var PipeMeasureDown4 = e.values[21];
// PIPE NUMBER 5
var PipeSize5 = e.values[22];
var PipeMaterial5 = e.values[23];
var PipeDirection5 = e.values[24];
var PipeMeasureDown5 = e.values[25];
// Calculate Invert Elevations:
var Dip1 = Elevation - PipeMeasureDown1;
var Dip2 = Elevation - PipeMeasureDown2;
var Dip3 = Elevation - PipeMeasureDown3;
var Dip4 = Elevation - PipeMeasureDown4;
var Dip5 = Elevation - PipeMeasureDown5;
// Build structure information
var firstLine = StructureType + " " + StructureSize + "\n";
var secondLine = "Rim=" + Elevation + "\n";
var thirdLine = PipeSize1 + " " + PipeMaterial1 + " I.E. " + PipeDirection1 + "=" + Dip1 + "'\n";
var fourthLine = PipeSize2 + " " + PipeMaterial2 + " I.E. " + PipeDirection2 + "=" + Dip2 + "'\n";
var fifthLine = PipeSize3 + " " + PipeMaterial3 + " I.E. " + PipeDirection3 + "=" + Dip3 + "'\n";
var sixthLine = PipeSize4 + " " + PipeMaterial4 + " I.E. " + PipeDirection4 + "=" + Dip4 + "'\n";
var seventhLine = PipeSize5 + " " + PipeMaterial5 + " I.E. " + PipeDirection5 + "=" + Dip5 + "'";
var Mtext = firstLine + secondLine + thirdLine + fourthLine + fifthLine + sixthLine + seventhLine;
var calcsheet = SpreadsheetApp.openById('-removed-').getSheetByName('Calculations');
var ss = SpreadsheetApp.getActiveSpreadsheet(); // ss is now the spreadsheet the script is associated with
var sheet = ss.getSheets()[1]; // sheets are counted starting from 0
// sheet is the second worksheet in the spreadsheet
var cell = sheet.getRange("A1");
cell.setValue(Mtext);
// Dump variable to logger log
// var dump = "Variable dumps: first the URL: " + PNEZD_fileURL + " and next the file ID alone: " + PNEZD_fileID + " and now the job number: " + JobNumber;
// Logger.log( dump );
// Logger.log(JobNumber);
// Logger.log("Data dump: " + PNEZD_field);
// Logger.log("Data dump: " + PNEZD_array[3][3]);
// Logger.log(StructureNumber + "," + Northing + "," + Easting + "," + Elevation);
}

How to write the result of a loop into a Google Sheet

Below code sends out emails including a table in the body with data rows and header in html. It also attaches the same data into an xlsx and pdf file. Some like it in pdf, some like it in the body of the email, some like it in xlsx so ...
I have 2 issue's with below code:
The result of the loop, table/rows, should be written to a google sheet (Export). This sheet will then be attached as PDF & XLSX to the email sent.
Currently the "Export" sheet is already attached but it's "empty" as the data is not yet written to the Export Sheet, that is the question how to?
I tried to add already the lines "xlsxTable += data[row][col];" in the code to catch the data but I don't think it's the proper way to do so.
Second issue is that sometimes the attachment (xlsx) is not "correctly" formatted and contains the following words: "This file might be un". (Google preview) When downloading the xlsx it's saying, file format not correct ... but the strange thing is, when sending out to 3 different emails 2 of them are OK, 1 is not, sometimes all are OK. Maybe this is timing issue and should include a pause.
Any help is welcome, Thanks!
Below code uses google sheets, with 4 sheet inside: Data, Emails, Parameters, Export.
Data Sheet
ID Name Amount Date
1000 Company 500.23 01/01/2019
2000 Company 500.23 01/01/2019
1000 Company 500.23 01/01/2019
3000 Company 500.23 01/01/2019
1000 Company 500.23 01/01/2019
2000 Company 500.23 01/01/2019
Emails Sheet
ID To Cc Bcc FirstName Subject Language BodyStart BodyEnd Sent SentDate
1000 Company1#email.com
2000 Company2#email.com
3000 Company3#email.com
Parameters Sheet contains just the ReplyTo & ReplyToName
Actual Code
function Statements_Attachments() {
//This section specifies the sheet and some fixed variables.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataRange = ss.getSheetByName("Data").getDataRange();
var emailRange = ss.getSheetByName("Emails").getDataRange();
var param = ss.getSheetByName("Parameters");
var data = dataRange.getValues();
var nameData = emailRange.getValues();
var lastCol = dataRange.getLastColumn();
var lastRow = emailRange.getLastRow();
var replyEmail = param.getRange("B2").getValue();
var replyName = param.getRange("B3").getValue();
var sentRange = ss.getSheetByName("Emails");
var startRow = 1;
var sent = "Y";
var ssA = SpreadsheetApp.getActive();
var ssID = ssA.getId();
var ssName = ssA.getName();
var sheetName = "Export"; //Fill in Sheet Name you want to Email
var shID = getSheetID(sheetName); //Get Sheet ID of Sheet Name
//This section below starts the loop comparing the key between the 2 sheets.
for (var i = 1; i < nameData.length; i++) {
var rows = nameData[i];
var emailAddress = rows[2];
var keyID = rows[0];
var ccMail = rows[3];
var bccMail = rows[4];
var bodyStart = rows[8];
var bodyEnd = rows[9];
var keyName = rows[1];
var subject = rows[6] ;
var emailSent = rows[10];
var xlsxTable = ""; //Variable used to collect the Data for pasting in "Export Sheet"
var exportTable = ""; //Variable used to paste Data in "Export Sheet"
var htmlTable = ""; // HTML body Table created to paste in Email
var htmlMessage = "";
var preTable = '<!DOCTYPE html><html>' + bodyStart ;
var postTable = '</html>';
for (row = 0; row < data.length; row++) {
if (row == 0){
for (col = 0; col < data[row].length; col++) {
if (col == 0) {
htmlTable += '<tr><th style="border-collapse: collapse;border: 1px solid black;background-color:#558EDB">' + data[row][col] + '</th>';
xlsxTable += data[row][col];
} else
if (col == lastCol - 1) {
htmlTable += '<th style="border-collapse: collapse;border: 1px solid black;background-color:#558EDB">' + data[row][col] + '</th></tr>';
xlsxTable += data[row][col];
} else {
htmlTable += '<th style="border-collapse: collapse;border: 1px solid black;background-color:#558EDB">' + data[row][col] + '</th>';
xlsxTable += data[row][col];
}
}
}
else if (data[row][0] == keyID) {
for (col = 0; col < data[row].length; col++) {
if (col == 0) {
htmlTable += '<tr><td style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td>';
xlsxTable += data[row][col];
} else
if (col == lastCol - 1) {
htmlTable += '<td style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td></tr>';
xlsxTable += data[row][col];
} else
if (col == 6) {
htmlTable += '<td align="right" style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td>';
xlsxTable += data[row][col];
} else
if (col == 20 || col == 21) {
htmlTable += '<td style="border-collapse: collapse;border: 1px solid black">' + Utilities.formatDate(data[row][col], "GMT", "dd-mm-yyyy") + '</td>';
xlsxTable += data[row][col];
} else {
htmlTable += '<td align="right" style="border-collapse: collapse;border: 1px solid black">' + data[row][col] + '</td>';
xlsxTable += data[row][col];
}
}
}
}
//The section below closes the table in the body and constructs the complete body.
htmlTable += '</tbody></table>';
htmlMessage = preTable + htmlTable + bodyEnd + postTable;
//The section below should paste the Data into the Export Sheet, to be used as basis for the xlsx & pdf attachment to the email.
exportTable = xlsxTable;
//How to write the result to the Export Sheet in columns and rows.
//The section below sets the variables for the Attachment.
var url = "https://docs.google.com/spreadsheets/d/"+ ssID + "/export?format=xlsx&id="+ ssID +"&gid="+ shID;
var urlPdf = url + "&portrait=true" + "&exportFormat=pdf";
var paramsP = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var paramsX = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blobPdf = UrlFetchApp.fetch(urlPdf, paramsP).getBlob();
var blobP = blobPdf.setName(sheetName + ".pdf");
var blobXlsx = UrlFetchApp.fetch(url, paramsX).getBlob();
var blobX = blobXlsx.setName(sheetName + ".xlsx");
//The section below retrieves alias email address to send as
var me = Session.getActiveUser().getEmail();// Log the aliases for this Gmail account.
var aliases = GmailApp.getAliases(); // Gets the alias from account
Logger.log(aliases); // Logs the alias
// The section below sends the actual emails
if (emailAddress != "" && emailSent != sent){ //If next email address needs to be different add: && nextEmail != emailAddress
if (aliases.length > 0){ // Prevents sending duplicates
GmailApp.sendEmail(emailAddress, subject, '', {
htmlBody: htmlMessage,
from : aliases[1],
cc : ccMail,
bcc : bccMail,
replyTo : replyEmail,
name : replyName,
attachments : [blobP, blobX],
});
// The section below puts a "Y" next to the row already processed.
sentRange.getRange(startRow + i, 11).setValue(sent);
sentRange.getRange(startRow + i, 12).setValue(new Date ());
//Utilities.sleep(1000);
SpreadsheetApp.flush(); // Make sure the cell is updated right away in case the script is interrupted
}
}
}
}
function getSheetID(name){
var sheetName = SpreadsheetApp.getActive().getSheetByName(name)
var sheetID = sheetName.getSheetId().toString()
return sheetID
}