Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

javascript - Concatenating strings in Google Apps Script

How do I get both values represented by i and j into the getSheetByName function?

Disclaimer: I am brand new at coding and am probably asking the wrong questions. My goal is to create a simple code that will delete sheets automatically by looping through the sheet names: Week 1, Week 2, etc.

Here's my code so far:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet()
  var i = "Week "
  var j = 32
  var mysheet = sheet.getSheetByName(i&j)
  sheet.deleteSheet(mysheet)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your code you have written i&j that's not the syntax to concat in Google apps script. Instead you can simply use i + j. For looping you'll need to use any loop, like for, while, do-while.

Combining these suggestions, here is my final suggestion.

Try something like this [By using 'try' here I mean, simply don't copy-n-paste and use. Try to understand and write your own code, curated for your specific need. Maybe that way, we'll grow/learn more]

function myFunction() {
  var START_WEEK = 1; //Put your starting week count here
  var END_WEEK = 2; //Put your ending week count here
  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet()
  var pre_name = "Week"
  var i;
  for (i = START_WEEK; i <= END_WEEK; i++) {
    try {
      spreadSheet.deleteSheet(spreadSheet.getSheetByName(pre_name + " " + i))
    } catch (exp) {
      //Maybe sheet with that name is not found
      Logger.log(exp.toString());
    }
  }
}

This code loop through all sheet whose name start with "Week " and then followed by week count, up till the end week count and if that's found it's deleting them.

Make sure you put in START_WEEK and END_WEEK properly.

Let me know if this doesn't work for you or if you have any query.

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...