简体   繁体   中英

IF Return Google Apps Script GoogleSheets

I have a simple application that monitors activity (onEdit) on tabs on a spreadsheet except for 2 tabs, call them 'Sheet1' and 'Sheet2'.#

Snippet from code is:

  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheetName = sheet.getName(); 
  var Sheet1 = ss.getSheetByName("Sheet1");
  var Sheet2 = ss.getSheetByName("Sheet2");
  if (sheetName == Sheet1 || sheetName == Sheet2) return;

This does not work and it will monitor changes on these sheets. By trying a different method:

  if (sheetName == Sheet1) return;
  if (sheetName == Sheet2) return;

Still does not work.

However, when I try just one, like:

  if (sheetName == Sheet1) return;

Then it will not monitor what is happening on Sheet1.

How can I make it stop looking at both sheets?

Thanks

You want to run return , when sheetName is Sheet1 or Sheet2 which are the sheet names. If my understanding is correct, how about this modification?

Modification points :

  • In your script, sheetName is string. About Sheet1 and Sheet2 , before var Sheet1 = ss.getSheetByName("Sheet1") and var Sheet2 = ss.getSheetByName("Sheet2") are run, those are strings. But after these were run, Sheet1 and Sheet2 become objects of Sheet. At this time, at if (sheetName == Sheet1 || sheetName == Sheet2) return; , "string" and "object" are compared. By this, the comparison what you want cannot be performed. If you want to retrieve "true" from this comparison, you can do it by changing to sheetName = "Sheet" . But I don't think this is what you want. So in order to solve this issue, I think that 2 patterns for your situation. Please check them and select the pattern you want.

Pattern 1

sheetName is compared by Sheet1 and Sheet2 which are the sheet names.

Modified script :

var sheetName = sheet.getName();
if (sheetName == "Sheet1" || sheetName == "Sheet2") return;

Pattern 2

Although I'm not sure about sheet of sheet.getName() from your question, if you want to compare the sheets after it confirms whether Sheet1 and Sheet2 are existing in the active spreadsheet, please modify as follows.

Modified script :

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = sheet.getName(); 
var Sheet1 = ss.getSheetByName("Sheet1");
var Sheet2 = ss.getSheetByName("Sheet2");
if ((Sheet1 && sheetName == Sheet1.getName()) || (Sheet2 && Sheet2.getName())) return;

Note :

  • In this modified script, Sheet1 && of Sheet1 && sheetName == Sheet1.getName() is used for checking the existence of Sheet1 . Sheet2 is the same as well.

If I misunderstand your question, I'm sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM