Google app script monitor spreadsheet selected ranges

前端 未结 2 736
耶瑟儿~
耶瑟儿~ 2021-01-28 05:11

I want to write a app script that can get the selected cells

and show it on the html input text.

example:

when I selected A1 cell, then the input text wi

相关标签:
2条回答
  • 2021-01-28 05:39

    I made this as a possible solution. The app script looks like this. It works quite well. Not sure if it is what you are looking for.

    function onOpen() {
      SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
          .createMenu('Custom Menu')
          .addItem('Show sidebar', 'showSidebar')
          .addToUi();
    }
    
    function showSidebar() {
      var html = HtmlService.createHtmlOutputFromFile('Page')
          .setTitle('My custom sidebar')
          .setWidth(300);
      SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
          .showSidebar(html);
    }
    
    function getActiveRange(){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName('Sheet1');
      var range = sheet.getActiveRange().getA1Notation();
      Logger.log(range)
      return range  
    }
    

    The side bar has function that calls every 200th of a second. Making it look like it is getting the data on mouse drag.

    <!DOCTYPE html>
    <html>
    <head>
        <base target="_top">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
        </script>
        <title></title>
    </head>
    <body>
            <input id="data"> 
            <script>
              $(document).ready(() => {
               setInterval(()=>{
               google.script.run.withSuccessHandler(log).getActiveRange();
               },200)    
              })       
              log(e) => {
                $('#data').val(e)
              }       
            </script> 
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-28 05:41

    New event added in April 2020:

    Ref: https://developers.google.com/apps-script/guides/triggers#onselectionchangee

    /**
     * The event handler triggered when the selection changes in the spreadsheet.
     * @param {Event} e The onSelectionChange event.
     */
    function onSelectionChange(e) {
      // Set background to red if a single empty cell is selected.
      var range = e.range;
      if(range.getNumRows() === 1 
          && range.getNumColumns() === 1 
          && range.getCell(1, 1).getValue() === "") {
        range.setBackground("red");
      }
    }
    
    0 讨论(0)
提交回复
热议问题