How to insert the email address by querying corresponding ID using Google App Scripts?

前端 未结 2 594
醉梦人生
醉梦人生 2020-12-12 07:51

In case of my current codes for doing MANUAL ENTRY, when I select a subject, a date and input maximum 4 student IDs at a time (e.g. 1802001, 1802002, 1802004 for example) an

2条回答
  •  隐瞒了意图╮
    2020-12-12 08:11

    Your task can be fulfilled by using an onEdit trigger.

    Code

    // Copyright 2020 Google LLC.
    // SPDX-License-Identifier: Apache-2.0
    
    function onEdit(e) {
        let currentSheet = e.range.getSheet().getName();
        let valsToSearchIn = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_WHERE_THE_IDS_ARE').getRange(ROW, COL, NO_ROWS, NO_COLS).getValues();
    
        if (currentSheet == 'SHEET_WHERE_YOU_INPUT_THE_IDS') {
            let inputValue = e.value;
            for (let i = 0; i < valsToSearchIn.length; i++)
                if (valsToSearchIn[i][0] == inputValue) 
                    e.range.setValue(SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_WHERE_YOU_INPUT_THE_IDS').getRange(i + ROW, COL).getValue());
                else
                    SpreadsheetApp.getUi().alert('Please input a valid student id!');
        }
    }
    

    Explanation

    The above code works by identifying the sheet in which an edit has been by making use of the e event object. If the name of this sheet is the same name as SHEET_WHERE_YOU_INPUT_THE_IDS, then the value which has been inputted is stored in the inputValue variable. Afterwards, it searches in the valsToSearchIn array - which is the array in which the student ids are stored, for the inputValue and if the search is successful, the corresponding email address will be set in the edited range. If the id is not found, then an alert will be displayed to the user.

    Note

    Please bear in mind that you will have to adjust the code above (especially the ranges and the names of the sheets) in order to fit with your requirements.

    Demo

    1. Before the onEdit(e) trigger

    SHEET_WHERE_THE_IDS_ARE

    SHEET_WHERE_YOU_INPUT_THE_IDS

    1. After the onEdit(e) trigger

    SHEET_WHERE_YOU_INPUT_THE_IDS

    Reference

    • Apps Script Event Objects;

    • Apps Script onEdit(e).

提交回复
热议问题