简体   繁体   中英

How to extract value from one sheet based on search criteria in another in Google Script?

So I have 2 sheets in a Google spreadsheet document.

SHEET 1 has one column with following data:

ID  
1
2
3
4
5
6
7
8
9
..

And then SHEET 2 has 2 columns with following data:

ID    EMAIL
1     s@abc.com
2     a@abc.com
7     f@abc.com
...etc

I need to run a script on "Form Submit" which does the following:

  1. Opens up Sheet 1 (where ID was recorded)
  2. Compare it with values Column 1 of 'Sheet 2' sequentially
  3. When match found extract the email address into variable "var"

Can someone please help me with this? Both these sheets are in the same google document.

Thank you!

Shashi

Not sure what you want to achieve here. If this 'lookup' is part of a wider onFormSubmit, you can create a fuction that is called when needed, passing in the ID and the spreadsheet.

function yourMainFunction() {
    var ss =
    ...
    var id =     
    var email = lookupEmail(id, ss)
    ....
    ...
}

function lookupEmail(id, ss) {

    var lookupSheet = ss.getSheets()[1]; //second sheet 
    var data = lookupSheet.getDataRange()
        .getValues()
    var email;
    for (var i = 0, len = data.length; i < len; i++) {
        if (data[i][0] == id) {  //id's are in the first column
            email = data[i][1]  //email is in the second column
        } else {
            email =  null; //if not found return null
        }
    }
    return email;
}

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