I'm trying to write code to save data and read data from telegram to google sheets using this code
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doPost(e) {
var data = JSON.parse(e.postData.contents);
var id = data.message.chat.id;
var username = data.message.chat.username;
var date = Utilities.formatDate(new Date(), "GMT+9", "dd/MM/yyyy");
var hour = Utilities.formatDate(new Date(), "GMT+9", "HH:mm:ss");
var text = data.message.text;
if (text.startsWith("/start")) {
sendText(id,"Hello " + username + ", welcome to my bot");
} else if (text.startsWith("/input")) {
const text = String(data.message.text).replace("/input ", "");
var item = text.split(",");
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheet1);
sheet.appendRow([date,hour,id,username,item[1],item[2],item[3],item[4],item[5],item[6],item[7],item[8],item[9]]);
sendText(id,"data has been saved");
} else if (text.startsWith("/search")) {
const text = String(data.message.text).replace("/search ", "");
var keyword = text.split(" ");
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheet2);
var data = sheet.getRange("A2:E").getValues();
var found = false;
for (var i = 0; i < data.length; i++) {
if (data[i][0] == keyword[1]) {
sendText(id, "Data found!\n" + "data1 = " + data[i][0] + "\n" + "data2 = " + data[i][1] + "\n" + "data3 = " + data[i][2] + "\n" + "data4 = " + data[i][3] + "\n" + "data5 = " + data[i][4]);
found = true;
}
}
if (!found) {
sendText(id,"data not found");
}
} else if (text.startsWith("/help")) {
sendText(id,"/input (date, hour, id, username, item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7])\n/search (keyword)");
}
}
I have tried to use openAi chat to help fix my code, but still not work.
Related
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);
}
}
It was actually a Google Sheets project, so I'm learning on the fly as best as I can, but I can't even format this code below correctly - ugh!)
The error I am receiving is this:
TypeError: Cannot read property 'getResponseCode' of undefined
doGet_Appraisal # Appraisal_Email.gs:64
And the code is below:
//1. Performing to generate the Payslip getting sheet contents
function doGet_Appraisal(range,shTabName) {
var blob,exportUrl,name,options,response,sheetTabId,ss,ssID,url_base,email,subject;
var folderId ="1o9WImzeKdzsek7DfZWD_qzFsI9yLoplz";
var milliseconds = 2000;
range = range ? range : "B1:R44";
ss = SpreadsheetApp.openById("sheet_ID");
shTabName = "Appraisal Payslip Template";
ssID = ss.getId();
sh = ss.getSheetByName(shTabName);
const body = "Dear Employee" + "\n\n" + "<p>" + "<b> Payslip for the month of January is Available </b>" + "</p>";
var htmlText = body.replace(/\n/g,'\n<br>');
var bioCode = sh.getRange('F12');
const values = [...new Set(bioCode.getDataValidation().getCriteriaValues()[0].getValues().flat())];
var first = values[0];
var number = values.length - 1;
bioCode.setValue(first);
//2. Looping the Emp_ID till null
for(i = 0;i < number;i++)
{
if (sh.getRange('F12').getValue().length > 0) {
var person = sh.getRange('F12').getValue();
sheetTabId = sh.getSheetId();
//3. Getting the Corresponfing EMail based on Emp_ID
email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Appraisal Payslip Template').getRange('N12').getValue().toString();
Utilities.sleep(milliseconds);
url_base = ss.getUrl().replace(/edit$/,'');
name = sh.getRange("S1").getValue();
name = name + ""
subject = `${name}`;
Logger.log('email: ' + email)
Logger.log('body: ' + body)
//4. Exporting the sheet as PDF (contents)
exportUrl = url_base + 'export?exportFormat=pdf&format=pdf' +
'&gid=' + sheetTabId + '&id=' + ssID +
'&range=' + range +
'&size=A4' +
'&portrait=true' +
'&fitw=true' +
'&sheetnames=false&printtitle=false&pagenumbers=true' +
'&gridlines=false' +
'&fzr=false';
//5. Authorizing email setup OAuthToken
options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
//6. Getting the sheet url and export as PDF
options.muteHttpExceptions = true;
response = UrlFetchApp.fetch(exportUrl, options);
//var response2 = UrlFetchApp.fetch(exportUrl, options).getBlob();
Logger.log(response.getResponseCode())
const nextValue = values[values.indexOf(bioCode.getValue()) + 1] || values[0];
bioCode.setValue(nextValue);
}
else {const nextValue = values[values.indexOf(bioCode.getValue()) + 1] ||
values[0];
bioCode.setValue(nextValue);
}
//7. If response code is not 200 return error exporting PDF
if (response.getResponseCode() !== 200) {
console.log("Error exporting Sheet to PDF! Response Code: " + response.getResponseCode());
return;
}
blob = response.getBlob();
blob.setName(name + '.pdf')
GmailApp.sendEmail(email, subject, htmlText,
{
htmlBody: htmlText,
attachments: [{
fileName: `${name}` + ".pdf",
//content: response2.getBytes(),
mimeType: "application/pdf"
}]
});
//pdfFile = DriveApp.getFolderById(folderId).createFile(blob);
}
}
This was worked recently but now throws error
TypeError: Cannot read property 'getResponseCode' of undefined
doGet_Appraisal # Appraisal_Email.gs:64
My current code is listed below (triggered by on change). It creates a calendar event when a new "lead" is entered in our lead sheet via AppSheet. It currently only runs when a new lead aka new row is added. I would like it to also run when the appointment date is added or modified, so if a lead is entered but appointment is not set up at that time, it can be entered later and the calendar event will be created. Therefore, I know that if (e.changeType == "OTHER") will need to be changed to if (e.changeType == "OTHER" || "EDIT") and that I can no longer use sheet.getLastRow().
My question is what should I replace sheet.getLastRow() with and most importantly, how will I call/reference the row that was impacted by:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("Y:Y");
if (e.changeType == "OTHER" || "EDIT")
Essentially, what do I need to set the current var lastRow equal to so that it will call the row where the change was made instead of the last row? (I will of course change the name of the variable from lastRow to something more applicable when I do so)
Original Code:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
// Calendar to output requests
var calendar = CalendarApp.getCalendarById('youremail#gmail.com');
// Creates an object from the last form submission
function getSubmission() {
this.timestamp = sheet.getRange(lastRow, 9).getValue();
this.accountNumber = sheet.getRange(lastRow, 10).getValue();
this.contactLastName = sheet.getRange(lastRow, 11).getValue();
this.contactFirstName = sheet.getRange(lastRow, 12).getValue();
this.contactPhoneNumber = sheet.getRange(lastRow, 15).getValue();
this.contactEmail = sheet.getRange(lastRow, 16).getValue();
this.userLastName = sheet.getRange(lastRow, 37).getValue();
this.userFirstName = sheet.getRange(lastRow, 38).getValue();
this.userPhoneNumber = sheet.getRange(lastRow, 39).getValue();
this.userEmail = sheet.getRange(lastRow, 40).getValue();
this.streetAddress = sheet.getRange(lastRow, 17).getValue();
this.city = sheet.getRange(lastRow, 18).getValue();
this.state = sheet.getRange(lastRow, 19).getValue();
this.zipCode = sheet.getRange(lastRow, 20).getValue();
this.type = sheet.getRange(lastRow, 21).getValue();
this.equipment = sheet.getRange(lastRow, 22).getValue();
this.typeOfLead = sheet.getRange(lastRow, 13).getValue();
this.sourceOfLead = sheet.getRange(lastRow, 14).getValue();
this.notes = sheet.getRange(lastRow, 23).getValue();
this.date = new Date(sheet.getRange(lastRow, 24).getValue());
this.appointmentStart = sheet.getRange(lastRow, 25).getValue();
this.appointmentEnd = sheet.getRange(lastRow, 26).getValue();
this.direction = sheet.getRange(lastRow, 27).getValue();
this.callOnWay = sheet.getRange(lastRow, 28).getValue();
return this;
}
// Creates a calendar event using the submitted data
function updateCalendar(request) {
request.date.setHours(request.appointmentStart.getHours());
request.date.setMinutes(request.appointmentStart.getMinutes());
var endTime = new Date(request.date);
endTime.setHours(request.appointmentEnd.getHours());
endTime.setMinutes(request.appointmentEnd.getMinutes())
var event = calendar.createEvent(
request.state + " " + request.direction + " EST " + request.contactLastName + ", " + request.contactFirstName + " " + request.callOnWay,
request.date,
endTime
)
.setLocation(request.streetAddress + " " + request.city + ", " + request.state + " " + request.zipCode
)
.setDescription("Account # " + request.accountNumber + "\n" + "\n" + request.contactFirstName + " " + request.contactLastName + "\n" + request.contactPhoneNumber + "\n" + request.contactEmail + "\n" + "\n" + "Notes: " + request.type + " - " + request.equipment + ". " + request.notes + ".\n" + "Lead: " + request.typeOfLead + " - " + request.sourceOfLead + "." + "\n" + "\n" + "Jim: Scanned:____ " + "Inv. Adj:____ " + "QB:____ " + "Est. SL:____" + "\n" + "\n" + "Tracy: QB:____" + " Scan:____" + " Letter:____" + " Lead Sheet:____" + " Ref. Check #:____"
)
}
// --------------Main--------------
function main() {
var request = getSubmission();
updateCalendar(request);
}
function runMain(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("Y:Y");
if (e.changeType == "OTHER") {
main();
}
}
I am still quite new to writing in App Script, so any help is greatly appreciated!
Updated code with suggestions from #YuriKhristich:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
// Calendar to output requests to
var calendar = CalendarApp.getCalendarById('youremail#gmail.com');
// Creates an object from the last submission
function getSubmission(row) {
var data = sheet.getRange(row,9,1,40).getValues();
this.timestamp = row[ 9];
this.accountNumber = row[10];
this.contactLastName = row[11];
this.contactFirstName = row[12];
this.contactPhoneNumber = row[15];
this.contactEmail = row[16];
this.userLastName = row[37];
this.userFirstName = row[38];
this.userPhoneNumber = row[39];
this.userEmail = row[40];
this.streetAddress = row[17];
this.city = row[18];
this.state = row[19];
this.zipCode = row[20];
this.type = row[21];
this.equipment = row[22];
this.typeOfLead = row[13];
this.sourceOfLead = row[14];
this.notes = row[23];
this.date = new Date(row[24]);
this.appointmentStart = row[25];
this.appointmentEnd = row[26];
this.direction = row[27];
this.callOnWay = row[28];
return this;
}
// Creates a calendar event using the submitted data
function updateCalendar(request) {
request.date.setHours(request.appointmentStart.getHours());
request.date.setMinutes(request.appointmentStart.getMinutes());
var endTime = new Date(request.date);
endTime.setHours(request.appointmentEnd.getHours());
endTime.setMinutes(request.appointmentEnd.getMinutes())
var event = calendar.createEvent(
request.state + " " + request.direction + " EST " + request.contactLastName + ", " + request.contactFirstName + " " + request.callOnWay,
request.date,
endTime
)
.setLocation(request.streetAddress + " " + request.city + ", " + request.state + " " + request.zipCode
)
.setDescription("Account # " + request.accountNumber + "\n" + "\n" + request.contactFirstName + " " + request.contactLastName + "\n" + request.contactPhoneNumber + "\n" + request.contactEmail + "\n" + "\n" + "Notes: " + request.type + " - " + request.equipment + ". " + request.notes + ".\n" + "Lead: " + request.typeOfLead + " - " + request.sourceOfLead + "." + "\n" + "\n" + "Jim: Scanned:____ " + "Inv. Adj:____ " + "QB:____ " + "Est. SL:____" + "\n" + "\n" + "Tracy: QB:____" + " Scan:____" + " Letter:____" + " Lead Sheet:____" + " Ref. Check #:____"
)
}
// --------------Main--------------
function main() {
var request = getSubmission(lastRow);
updateCalendar(request);
}
function runMain(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("Y:Y");
if (e.changeType == "OTHER") {
main();
}
}
function onEdit(e) {
if (e.range.columnStart != 25) return;
var request = getSubmission(e.range.rowStart);
updateCalendar(request);
}
Receiving the error message "TypeError: Cannot read property 'getHours' of undefined" when adding a new lead or editing appointment date.
runMain is being triggered via the installable trigger On Change.
Will an On Edit trigger need to be implemented to run the onEdit function or is that repetitive?
You can create another installable trigger onEdit (either manually or in Apps Script) to check which row was edited and then call getSubmission with that row number as parameter.
function getRow(e) {
var currentRow = e.range.getRow();
var request = getSubmission(currentRow);
updateCalendar(request);
}
Try to change the functions getSubmission() this way:
function getSubmission(row) { // <-- add 'row' argument here
var data = sheet.getRange(row,9,1,40).getValues(); // make one call to server instead of 24
this.timestamp = row[ 9];
this.accountNumber = row[10];
this.contactLastName = row[11];
this.contactFirstName = row[12];
this.contactPhoneNumber = row[15];
this.contactEmail = row[16];
this.userLastName = row[37];
this.userFirstName = row[38];
this.userPhoneNumber = row[39];
this.userEmail = row[40];
this.streetAddress = row[17];
this.city = row[18];
this.state = row[19];
this.zipCode = row[20];
this.type = row[21];
this.equipment = row[22];
this.typeOfLead = row[13];
this.sourceOfLead = row[14];
this.notes = row[23];
this.date = new Date(row[24]);
this.appointmentStart = row[25];
this.appointmentEnd = row[26];
this.direction = row[27];
this.callOnWay = row[28];
return this;
}
Change the main() function this way:
function main() {
var request = getSubmission(lastRow); // <-- add 'lastRow' argument here
updateCalendar(request);
}
And add the onEdit() function:
function onEdit(e) {
if (e.range.columnStart != 25) return; // if column Y
// probably it makes sense to check the name of the sheet as well
var request = getSubmission(e.range.rowStart);
updateCalendar(request);
}
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);
}
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.