首页 > 解决方案 > 如何将代码从 onOpen with menu 更改为 onEdit

问题描述

我正在尝试更改以下代码,以便它运行 onEdit 而不是 onOpen 并创建一个菜单。我只想在将 ISBN 输入“A”列时自动填充信息。

s = SpreadsheetApp.getActiveSheet();

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Book Menu')
      .addItem('Get Book Details', 'getBookDetails')
      .addToUi();
}

function getBookDetails(isbn) {

  // Query the book database by ISBN code.
  activeCell = s.getActiveCell();
  value = activeCell.getValue();
  isbn = isbn || value.toString(); // Steve Jobs book 

  // Not a valid ISBN if not 13 or 10 digits long.
  if(isbn.match(/(\d{13}|\d{10})/) == null){
    throw new Error( "Not a valid ISBN: " + isbn);
  }
  var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
  var response = UrlFetchApp.fetch(url);
  var results = JSON.parse(response);
  if (results.totalItems) {

    // There'll be only 1 book per ISBN
    var book = results.items[0];

    var title = (book["volumeInfo"]["title"]);
    var subtitle = (book["volumeInfo"]["subtitle"]) || "*No Subtitle";
    var authors = (book["volumeInfo"]["authors"]);
    var printType = (book["volumeInfo"]["printType"]);
    var pageCount = (book["volumeInfo"]["pageCount"]);
    var publisher = (book["volumeInfo"]["publisher"]);
    var publishedDate = (book["volumeInfo"]["publishedDate"]);
    var webReaderLink = (book["accessInfo"]["webReaderLink"]);

    //Logger.log(book);
    results = [[title, subtitle, authors, printType, pageCount, publisher, publishedDate, webReaderLink]];

  }else{
    results = [["-", "-", "-", "-", "-", "-", "-", "-"]];
  }
  s.getRange(activeCell.getRow(), activeCell.getColumn() + 1, 1, results[0].length).setValues(results);
}

标签: apigoogle-apps-scriptgoogle-sheets

解决方案


推荐阅读