0

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 will show A1

also if I selected a range between A1 to B11, then it will show A1:B11

I know getActiveRange().getA1Notation() can get the cell.

But how to monitor the drag select event?

Max
  • 4,439
  • 2
  • 18
  • 32

2 Answers2

2

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>
Jason Allshorn
  • 1,625
  • 1
  • 18
  • 27
0

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");
  }
}
shreyansp
  • 723
  • 1
  • 7
  • 16