Home > Software engineering >  Get Google Sheet by ID or Name, but not from active sheet?
Get Google Sheet by ID or Name, but not from active sheet?

Time:02-23

Can i get this script to work from sheet id or sheet name

This script works when i use the active spreadsheet but i want it to get it from the spreadsheet name or the sheet id. If i add .getSheetByName("Test") to line 2 it returns "TypeError: Cannot read property 'getRange' of null"

i am running the script from the sheet named "test" and there is a value in cell a1

Thanks in advance for the help

function CheckPrice() {
var priceRange = SpreadsheetApp.getActiveSpreadsheet().getRange("A1").getValue();
var ui = SpreadsheetApp.getUi();
if (priceRange < 10){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getRange("A2");
var emailAddress = emailRange.getValue();
var message = 'This is your Alert email!';
var subject = 'Your Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}

} ```

CodePudding user response:

Change twice SpreadsheetApp.getActiveSpreadsheet() to SpreadsheetApp.getActiveSpreadsheet().getSheetByName('mySheetName')

For instance

function CheckPrice() { 
  var priceRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test').getRange("A1").getValue();  
  // get value from cell a1 
  var ui = SpreadsheetApp.getUi(); 
  if (priceRange < 10){ 
    var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test').getRange("A2"); 
    // get email from cell a2 
    var emailAddress = emailRange.getValue(); 
    // Send Alert Email. 
    var message = 'This is your Alert email!';  
    var subject = priceRange   " %up"; 
    // adds cell value to subject 
    MailApp.sendEmail(emailAddress, subject, message); }  
}
  • Related