This question already has answers here:
GAS "On edit" trigger not running when edited from API
(2 answers)
Installable OnEdit not being called in Stock spreadsheet
(1 answer)
Closed 10 months ago.
I wrote a script that is supposed to automatically send a list from a google sheet via email when the value of cell E7 is above 1.
It works if I change the value of E7 manually.
But when the data is transfered into the google sheet via an external application, it doesn't work. (I already set up a trigger)
What an I doing wrong? Can anyone help me with this?
function FunzioneFE(e) {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Foglio2");
var Cella = sheet.getRange("E7").getValue();
{
if(Cella > 1){
{
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio2").getRange("C2");
var emailAddress = emailRange.getValue();
var Text = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio2").getRange("D2");
var typ = Text.getValue();
var aliases = GmailApp.getAliases();
Logger.log(aliases)
var ws = ss.getSheetByName("Foglio2");
var h1 = ws.getRange("D2").getValue();
var headers = ws.getRange("A1:B1").getValues();
var descr = "FoodEngel"; //headers[0][0];
const tipo = headers[0][1];
var lr = ws.getLastRow();
var tableRangeValues = ws.getRange(2,1,lr-1,2).getValues();
var htmlTemplate = HtmlService.createTemplateFromFile("email");
var file = SpreadsheetApp.getActive();
var sheet = file.getSheetByName("Foglio2");
htmlTemplate.h1 = h1;
htmlTemplate.descr = descr;
htmlTemplate.tipo = tipo;
htmlTemplate.tableRangeValues = tableRangeValues;
var htmlForEmail = htmlTemplate.evaluate().getContent();
console.log(htmlForEmail);
GmailApp.sendEmail(
emailAddress,
typ,
'Bitte Lesen.',{
htmlBody: htmlForEmail,
name: "FoodEngel",
from: aliases[0]
})};
}}}
Related
This question already has answers here:
onEdit() trigger is unable to create a new Spreadsheet
(1 answer)
Google Sheets OnEdit() - You do not have permission to call a service
(2 answers)
Closed 7 months ago.
I write a script and it works fine if you run them separately from app script (RUN bottom). If I run it combined with the "run" bottom in app script it is working, when a enable the checkbox in the sheet, it is not working at all, clearall() is always working, addrecord() is working if I put it before var checkexist = ... , the other 2 are not working (running).
What is wrong here?
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("KLANTinput");
var checkadd = sheet.getRange("AI3").getValue();
if (checkadd === 1) {
var checkexist = sheet.getRange("X2").getValue();
if (checkexist === 0) {
addContactPhoneAndCreateFolder();
Utilities.sleep(500);
createNewFolderInGoogleDrive();
Utilities.sleep(500);
}
addrecord();
Utilities.sleep(500);
clearall();
var checkstate = sheet.getRange("AH3");
checkstate.setValue("FALSE");
}
}
function addContactPhoneAndCreateFolder() {
var sheet = SpreadsheetApp.getActiveSheet();
//var sheet = ss.getSheetByName("KLANTinput");
var first_name = sheet.getRange("J5").getValue();
var last_name = sheet.getRange("AD5").getValue();
var email = sheet.getRange("J15").getValue();
var adres = sheet.getRange("J7").getValue().concat(" ").concat(sheet.getRange("Z7").getValue()).concat(" ").concat(sheet.getRange("J9").getValue()).concat(" ").concat(sheet.getRange("AD9").getValue());
var phone = sheet.getRange("J13").getValue();
Logger.log(adres);
var contact = ContactsApp.createContact(first_name, last_name, email);
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(ContactsApp.createContact(first_name, last_name, email));
var contact = ContactsApp.findByEmailAddress(email);
contact.setHomeAddress(adres);
contact.setPrimaryEmail(email);
//contact.setWorkAddress(adres);
contact.setHomePhone(phone);
}
function createNewFolderInGoogleDrive() {
var sheet = SpreadsheetApp.getActiveSheet();
//var sheet = ss.getSheetByName("KLANTinput");
var folderName = sheet.getRange("J5").getValue().concat(" ").concat(sheet.getRange("AD5").getValue()).concat(" ").concat(sheet.getRange("J9").getValue()).concat(" ").concat(sheet.getRange("AD9").getValue()).concat(" ").concat(sheet.getRange("AD19").getValue());
var folder = DriveApp.getFolderById("sheetID");
//Logger.log(folderName);
var nfolder = folder.createFolder(folderName);
}
function addrecord() {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = sss.getSheetByName("KLANTinput");
var datasheet = sss.getSheetByName("KLANTpredb");
var values = [[sheet.getRange("C2").getValue(), //DATE + TIME
sheet.getRange("J3").getValue(), //DATE
sheet.getRange("K2").getValue(), //DD
sheet.getRange("N2").getValue(), //MM
sheet.getRange("Q2").getValue(), //YY
....
Logger.log(values)
//var roow = datasheet.getLastRow()
//Logger.log(roow)
datasheet.getRange(datasheet.getLastRow() + 1, 1, 1, 45).setValues(values);
}
I'm automating my google sheets to send out emails automatically and I can't figure out how to compare a variable array to a column in my google sheets. I keep getting all values returned rather than just the ones in my array when I put it in an 'IF' statement.
I want my code to only show data that is in my gEnglish variable but instead shows me all data. I was also wondering how I'd be able to send emails based on regions to users.
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Main").activate();
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var decisionOne = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(1,1).getValue();
var decisionTWO = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(2,1).getValue();
var decisionThree = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(3,1).getValue();
var decisionFour = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(5,1).getValue();
var decisionFive = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Templates").getRange(4,1).getValue();
var gEnglish = ["IT","US","GB","UK"];
var gSpanish = ["SP"];
var user1 = ["JP","SK","IND","RU"];
var user2 = [gEnglish,"UK"];
var user3 = [gSpanish, "BR", "PT"];
var user4 = ["FR", "DE","IT"];
for (var i = 2;i<=lr;i++){
var type = ss.getRange(i,6).getValue();
var region = ss.getRange(i, 5).getValue();
var decision = ss.getRange(i,15).getValue();
//I used to have if(region == gEnglish)
if(gEnglish.includes(region[i]) ){
var channel = ss.getRange(i,3).getValue();
var decision = ss.getRange(i,15).getValue();
var url = ss.getRange(i, 9).getValue();
var name = ss.getRange(i,11).getValue();
var messageBody = {};
var subjectLine = "blahblahblah";
}
}
}
If my array only has one value inside it works fine but as soon as I put more I just get all values returned.
What am I doing wrong?
Putting a column into a flat array.
function col2array() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const vA=sh.getRange(1,1,sh.getLastRow(),1).getValues().flat();
}
In Google Apps Script a column looks like:
[[Row1],[Row2],[Row3],[Row4]....]
function lookingforarrayvaluesinacolumn() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const vA=sh.getRange(1,1,sh.getLastRow(),1).getValues();
const coolpeople = ["p1","p2"];
vA.forEach(function(r,i){
if(coolpeople.indexOf(r[0])!=-1) {
//the r[0] is a cool person
}
});
}
How to search a column on a sheet for a value, and if the value is there continue code? I am trying to make an update system to check to see if their email is on a sheet. If their email is on a sheet then it will check if their system version is up to date. If the system is not to up to date it will then copy their data, delete their current sheet, create a copy from an example then put in their data. If the user does not have the system it will create one for them. It seems to continuously skip Checking their email.
My code uses URLs and IDs but I have taken them out for obvious reasons. Below is an example of the beginning of my code.
function readlog()
var user = Session.getEffectiveUser().getUsername();
var email = Session.getEffectiveUser().getEmail();
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = sheet.getSheetByName('8th grade')
var active = sheet.getRange('8th grade!b3:b').getValues()
if (email == active) {
//do something
}
Here is a full version of my code:
function readlog(){
var user = Session.getEffectiveUser().getUsername();
var email = Session.getEffectiveUser().getEmail();
var timezone= "CST";
var date = Utilities.formatDate(new Date(),timezone, "E MMM dd,yyyy HH:mm:ss");
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var sheet = sheet.getSheetByName('8th grade')
var active = sheet.getRange('8th grade!b3:b').getValues()
if (email == active) {
var container = DriveApp.getFoldersByName('Reading Log')
var fid = DriveApp.getFoldersByName('Reading Log').getId()
var version = sheet.getRange('8th grade!a1')
var update = container.getDescription();
if (update == version) {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('You already have a reading log, and you have the most recent update!', ui.ButtonSet.OK);
} else {
var contents = container.getFiles();
var files = DriveApp.getFolderById(fid).searchFiles(
'title contains "Reading log"');
while (files.hasNext()) {
var file = files.next();
var logtoupdate = file.getUrl;
}
var ss = SpreadsheetApp.openByUrl(logtoupdate);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var logrange = sheet.getRange('8th Grade!e5:o').getValues()
SpreadsheetApp.getActiveSpreadsheet().deleteActiveSheet();
var master = DriveApp.getFileById(URL_);
var read = master.makeCopy("Reading Log",container);
var target = read.getRange('8th Grade e5:o').setValues(logrange);
var range = sheet.getRange("A1:B2");
range.setValues([[50, 100]]);
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
}
} else {
var ss = SpreadsheetApp.openByUrl(URL_);
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var targetFolder = DriveApp.createFolder("Reading Log");
var eighth = DriveApp.getFileById(URL_);
var share = eighth.makeCopy("(Name): 8th Grade Reading Log",targetFolder);
var master = DriveApp.getFileById(URL_);
var read = master.makeCopy("Reading Log",targetFolder);
var folder = sheet.getRange('8th grade!a1');
targetFolder.setDescription(folder);
var idsheet = read.getUrl();
var idshare = share.getUrl();
var idfolder = targetFolder.getUrl()
sheet.appendRow([user,email,date,idfolder,idsheet,idshare]);
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Your Reading log is created. There is now a folder in your google drive called Reading log. Have Fun Reading!', ui.ButtonSet.OK);
}
}
Short answer
Instead of email == active use active.join('|').split('|').indexOf(email)
Explanation
getValues() return a two dimensional array.
join('|') convert this array into an string using | as separator.
split('|') convert the above string into an (one dimension) array.
indexOf(email) returns the index of the email value on the above array. If the email value is not found, -1 is returned.
On a comparison -1 is parsed as false.
This question already has an answer here:
Not allowed to execute sendEmail() from custom function, but OK in script editor
(1 answer)
Closed 7 years ago.
When I change something in my spreadsheet, the onEdit() trigger runs, and I can see all the msgbox's that I put in my code.
My function stops at this line
MailApp.sendEmail(emailAddress, subject, message);
I never see the message 'Email sent!', and get an error in the EXECUTION TRANSCRIPT:
You do not have permission to call sendEmail
If I run the script directly in the script editor, everything works fine...
Here is my code:
function onEdit() {
var sheet = SpreadsheetApp.getActiveSheet();
var sheetname = sheet.getName()
var AcCellRange = sheet.getActiveCell()
var AcCol = AcCellRange.getColumn()
var AcRow = AcCellRange.getRow()
if (sheetname=="Questions/Réponses") {
//Browser.msgBox(AcCol+' / '+AcRow)
//liste d'instructions
//Boucle si les colonne sont comprise dans le range
if ((AcCol==3) || ((AcCol==7))){
//Browser.msgBox(AcCol)
if (AcRow > 7){
//Browser.msgBox(AcRow)
sendEmails()
}
}
}
else
{}
}
function sendEmails() {
Browser.msgBox('SendEmails')
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('ListCourriel');
Browser.msgBox('SendEmails2')
var sheetDonnee = spreadsheet.getSheetByName('Questions/Réponses');
var RangeProjet = sheetDonnee.getRange(1, 3)
var NoProjet = RangeProjet.getValue()
var RangeProjet = sheetDonnee.getRange(4, 3)
var ProjName = RangeProjet.getValue()
Browser.msgBox('SendEmails3')
var startRow = 2; // First row of data to process
var LastRows = sheet.getRange(1,4)
var numRows = LastRows.getValue(); // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
Browser.msgBox('SendEmails4')
//Permet d'aller cherche les info de la ligne active
var ActiveCellRange = sheetDonnee.getActiveCell()
var ActiveRows = ActiveCellRange.getRow()
var NoLigne = sheetDonnee.getRange(ActiveRows,1)
var sDep = sheetDonnee.getRange(ActiveRows,2)
var sDate = sheetDonnee.getRange(ActiveRows,4)
var sInitiale = sheetDonnee.getRange(ActiveRows,5)
var sQuestion = sheetDonnee.getRange(ActiveRows,3)
Browser.msgBox('SendEmails5')
var rDate = sheetDonnee.getRange(ActiveRows,9)
var rInitiale = sheetDonnee.getRange(ActiveRows,10)
var rReponse = sheetDonnee.getRange(ActiveRows,7)
Browser.msgBox('SendEmails6')
var subject = 'Modif. Question/Réponse - Projet: ('+NoProjet+') '+ProjName;
var message = "No Ligne : "+NoLigne.getValue()+String.fromCharCode(10)+String.fromCharCode(10)+"Reponsable : "+sInitiale.getValue()+String.fromCharCode(10)+"Date : "+sDate.getValue()+String.fromCharCode(10)+"Question : "+String.fromCharCode(10)+sQuestion.getValue()+String.fromCharCode(10)+String.fromCharCode(10)+"************************************"+String.fromCharCode(10)+String.fromCharCode(10)+"Reponsable : "+rInitiale.getValue()+String.fromCharCode(10)+"Date : "+rDate.getValue()+String.fromCharCode(10)+"Réponse : "+String.fromCharCode(10)+rReponse.getValue()
//Browser.msgbox(subject)
Browser.msgBox('SendEmails7')
for (i in data) {
Browser.msgBox('SendEmails8')
var row = data[i];
var emailAddress = row[0]; // First column
Browser.msgBox('SendEmails9')
MailApp.sendEmail(emailAddress, subject, message);
Browser.msgBox('Email sent')
}
}
The permissions are different when running a SIMPLE onEdit() trigger. By contrast, there is an INSTALLABLE trigger. Here is the documentation for simple trigger restrictions:
Google Documentation - Triggers - Restrictions
The documentation states:
They (a SIMPLE trigger) cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization
You need to set up an installable trigger to be able to send the email.
In the EDIT menu, choose, CURRENT PROJECTS TRIGGERS.
Name your function something different than onEdit.
This question already has an answer here:
How to fix 'TypeError: Cannot call method "getRange" of null' in Google Apps Script
(1 answer)
Closed 5 months ago.
I'm trying to publish this code, but everytime when I run this code I get an error
Cannot call method"getDataRange" of null.
Here is my code
function
doGet() {
var ss = SpreadsheetApp.openById('sheet id');
var sheet = ss.getSheetByName('sheet name');
var data = sheet.getDataRange();
var dateFilter= Charts.newCategoryFilter().setFilterColumnIndex(0).build();
var ageFilter = Charts.newNumberRangeFilter().setFilterColumnIndex(7).build();
var transportFilter = Charts.newCategoryFilter().setFilterColumnIndex(2).build();
var nameFilter = Charts.newStringFilter().setFilterColumnIndex(1).build();
var tableChart = Charts.newTableChart().setDimensions(700, 300)
.setDataViewDefinition(Charts.newDataViewDefinition().setColumns([0,1,2,3,4,5,6,7]))
.build();
var pieChart = Charts.newPieChart()
.setDataViewDefinition(Charts.newDataViewDefinition()
.setColumns([1,7])).build();
var dashboard = Charts.newDashboardPanel().setDataTable(data)
.bind([dateFilter,ageFilter, transportFilter, nameFilter], [tableChart, pieChart])
.build();
var app = UiApp.createApplication().setHeight(50);
var todaysdate = new Date();
app.add(app.createLabel(todaysdate));
app.add(app.createHTML('<h1 style="text-align:center;">DEMO</h1>'));
var filterPanel = app.createHorizontalPanel();
var chartPanel = app.createHorizontalPanel();
filterPanel.add(dateFilter).add(ageFilter).add(transportFilter).add(nameFilter).setSpacing(10);
chartPanel.add(tableChart).add(pieChart).setSpacing(50);
dashboard.add(app.createVerticalPanel().add(filterPanel).add(chartPanel));
app.add(dashboard);
var service = ScriptApp.getService();
service.enable(service.Restriction.ALL);
return app;
}
The error indicate sheet is null. Make sure you are using the correct sheet name in var sheet = ss.getSheetByName('sheet name');. Copy and paste the sheet name from the google doc if there are invisible characters.