简体   繁体   中英

Google Sheets script: how do I run a script only on the sheets whose names contain particular text?

(On Google Sheets) I want to create a script that runs only on certain sheets in a spreadsheet. To do this I have created a script that creates an array of sheet names whose names (defined as a variable curSheetName) fit the following condition:

if(curSheetName == "CM:")

so currently the sheet name must equal "CM:", however I want it to be so that the script runs on all sheets that CONTAIN the text "CM:" in their title, but I can't find how to write that syntactically. In MySQL it is '%CM:%', in GSheet formulas you just use asterisks..

Here is my code:

// Get list of sheet names in an array format
function sheetnames() {
  // Define array
  var out = new Array()
  // Get sheets
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  // Work through each sheet one at a time
  for (var i=0 ; i<sheets.length ; i++) {
    // define the current sheet
    var curSheetName = sheets[i].getName();
    // determine if matches criteria
    if(curSheetName == "CM:") { //***************** NEED HELP HERE
      // put into array if matches criteria
      out.push( [ sheets[i].getName() ] );
//      RUN FUNCTION HERE
    }
  }
}

Any help appreciated, Cheers, Mike

You can use the JavaScript Array.indexOf() method to achieve this.


Example:

if (curSheetName.indexOf('CM:') !== -1) {
  ...
}

Documentation:

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