简体   繁体   English

Function 在 Google 表格脚本的另一个电子表格中搜索表格

[英]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?有没有办法制作一个 function 在另一个电子表格中搜索特定工作表名称以知道它是否存在?

Explanation:解释:

  • You can use openById(id) to get the spreadsheet based on its id.您可以使用openById(id)根据其 ID 获取电子表格。

  • Use getSheetByName(name) which returns null if there is no sheet with the given name.如果没有具有给定名称的工作表,则使用返回nullgetSheetByName(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?您是否有要在其中搜索的工作表的电子表格 ID? This will get you the id of the sheet you are looking for if it exists如果存在,这将为您提供要查找的工作表的 ID

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;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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