问题
I need my google sheet to send emails every time a condition becomes true. In this case, every time value of C2 is lower than value of J2. On the cell L2 there is the email address.
The code (found online and just edited)
function CheckPrice() {
var LastPriceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("C2");
var LastPrice = LastPriceRange.getValue();
var EntryLimitRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("J2");
var EntryLimit = LastPriceRange.getValue();
var StockNameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("B2");
var StockName = LastPriceRange.getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts").getRange("L2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var message = 'Ticker ' + StockName + ' has triggered the alert';
var subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
With this code I don't receive any error, but I don't even receive the email. I granted permissions as requested when I run the script for the first time.
On L2 I put the same email address I granted permission (I send email to myself). I did a try even putting a secondary email address I have.
Can you please show me what's wrong ?
回答1:
Issues:
See the first lines of your code where you define
LastPrice
,EntryLimit
andStockName
. All of them are coming from the same range:LastPriceRange
.I also removed all the unnecessary calls in your script. There is no need to call
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts")
so many times when you can just put it in a variable and use that variable instead.Also, you don't need to define unnecessary variables. For example, you can get the value of a cell with one line:
sh.getRange("B2").getValue()
.
Solution:
function CheckPrice() {
const sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Alerts");
const LastPrice = sh.getRange("C2").getValue();
const EntryLimit = sh.getRange("J2").getValue();
const StockName = sh.getRange("B2").getValue();
// Check totals sales
if (LastPrice < EntryLimit){
// Fetch the email address
const emailAddress = sh.getRange("L2").getValue();
// Send Alert Email.
const message = 'Ticker ' + StockName + ' has triggered the alert';
const subject = 'Stock Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
}
If you want an email to be sent when you edit a particular cell, then you need to transform the aforementioned solution to an onEdit(e) trigger. If you want a time basis trigger then you can just use the solution above directly.
来源:https://stackoverflow.com/questions/63992674/google-sheet-send-email