简体   繁体   中英

Function to search for a sheet in another spreadsheet in Google Sheets Scripts

Is there any way to make a function that searches for a specific sheet name in another spreadsheet to know if it exists or not?

Explanation:

  • You can use openById(id) to get the spreadsheet based on its id.

  • Use getSheetByName(name) which returns null if there is no sheet with the given name. Therefore you can directly use that to check whether a sheet exists or not.

Solution:

function myFunction() {
  
  const sheetNameToCheck = "Sheet3"
  const anotherSpreadsheet = SpreadsheetApp.openById("ID of another Spreadsheet");
  const sheet = anotherSpreadsheet.getSheetByName(sheetNameToCheck);
  
  if(sheet){
    console.log(`${sheetNameToCheck} exists!`);
  }
  else{
    console.log(`${sheetNameToCheck} does not exist!`);
  }
  
}

Do you have the Spreadsheet ID of the sheet you want to search in? This will get you the id of the sheet you are looking for if it exists

function searchSpreadsheet() {

  //What is your search term
  var searchTerm = "Sheet3";

   //Where do you want to search
   var destinationSpreadsheet = SpreadsheetApp.openById("Your destination spreadsheet id");
  var destinationSheet = destinationSpreadsheet.getSheets();

  // Search spreadsheet and log name and id 
  for (i=0; i<destinationSheet.length; i++){
    if (searchTerm == destinationSheet[i].getSheetName()){
      console.log("Sheet found. Sheet name: "+destinationSheet[i].getSheetName()+". Sheet id: "+destinationSheet[i].getSheetId())
      break;
    }
  }
}

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