IF Function - Google Scripts

2019-08-09 02:52发布

I'm struggling to get my Script to run an IF function. Basically I want to run a script based on specific cell contents.

I would like an IF function to run based on this and have written the following code:

function sendemail () {


 var ss = SpreadsheetApp.getActiveSpreadsheet(); 
 var s = SpreadsheetApp.getActiveSheet(); 

 var targetSheet = ss.getSheetByName("Response");
 var vCodes = ss.getSheetByName("Codes") 

 var vResults = targetSheet.getRange("E2").getValues(); 
 var emailAddresses = targetSheet.getRange("B2").getValues() 

 var dataRange = vCodes.getRange(1, 1, vResults, 1).getValues();
 var subject = "Here are your Wi-Fi Codes!";
 var vLength = vCodes.getRange("C2").getValues();  

 if (vLength == "24 hours"){
 MailApp.sendEmail(emailAddresses, subject, dataRange);
 targetSheet.deleteRows(2);
 vCodes.deleteRows(1,vResults);
    }
}

If the value in C2 is "24 hours" I'd like it to send an e-mail. At the moment when I run the script there are no errors but it doesn't send any e-mail as the IF function obviously isn't running correctly.

If I edit the code to say:

 if (vLength == "")

then the e-mail sends. It doesn't seem to recognise "24 hours" as valid data to look up.

  • Can anyone see what I'm doing wrong?

1条回答
淡お忘
2楼-- · 2019-08-09 03:51

The value you get from the cell is not what you think because you are using getValues() with an 's' and you probably know that this method always returns an array of arrays, even when a single cell is defined as range.

You have 2 options :

  1. use getValue() to get the string content of the cell
  2. use getValues()[0][0] to get the first (and only) element of this array.

I would suggest the first solution as I think it's generally a good idea to use appropriate methods... getValue() for single cell and getValues() for multiple cells... I didn't check further but I'm pretty sure it will work with this change (applies to vResults , emailAddresses and vLength) .

It would also be careful to ensure that vResults is a number since you use it to define a range... you could use Number(vResults) as a safety measure.

查看更多
登录 后发表回答