简体   繁体   中英

How query/search for information from one Google spreadsheet to another spreadsheet using GAS?

I would like to create a Google Apps Script to do the following: When I select a cell containing the name of a person in a spreadsheet (a spreadsheet that records sales, for example), and use a menu button to call the function, the script does a search (a query) using the person's name (or number of his document) in another spreadsheet that stores complete consumer data and that contains all the information that I need from that consumer to generate a contract or a payment receipt. What is the best strategy to implement this search for information from one spreadsheet in another spreadsheet using Google Apps Script? Do you have some script sample with a implementation similar to this? THANK YOU in advance for any help/guidance!

There is no event triggered by a cell selection, you'll have to use a menu item or a button to call the function or, if it is acceptable for your use case, edit the cell to trigger an onEdit event.

The 'search part' is actually very simple, the data being on the spreadsheet itself or in another one has no importance, it will simply change the way you access data ( getActiveSpreadsheet or openById() ). From there just get all the values and do a search in the resulting 2D array.


EDIT following your comment : here is an example of such a code that returns the range of the found cell ( and we get the A1 notation but we could getValue() as well of course.) .

function test(){ // to test the find function with an argument, 'any' in this case 
  var result = findItem('any');
  if(result){Logger.log(result.getA1Notation())}else{Logger.log('no luck !')};
}

function findItem(item){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = ss.getDataRange().getValues()
  for(var n = 0;n<data.length;++n){
    if(data[n].indexOf(item)>-1){ // this is a "strict" find, ie the value must be the entire search item. If you want to do partial match you should compare differently...
      return (ss.getRange(n+1,data[n].indexOf(item)+1)); // if found return the range. note the +1 because sheets have 1 index while arrays have 0 index
    }
  }
  return false;// if we come to the end of sheet without result...
}

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