How do I change the cell a user is editing? (Googl

2019-08-21 04:39发布

问题:

The tool I'm working on displays a list of Google Drive files. Users are prompted to put an "X" next to every file they want to have included in a Master Library of document links. After the files are added I delete every row that has an "X".

While testing today I noticed that if I type "X" in a cell but do NOT hit ENTER before clicking the "Add Selected Files to Library" button, that file doesn't get added. That's fine, the problem is that there is still a selected cell with an "X" in it, but it's off by one.

Is there a way to clear the cell being edited? Or move the cell being edited to account for the deleted row?

If it helps, here's my code (I'm obviously not a professional coder, so thanks for your patience):

function addToLibrary() {
  var x = 2;
  var added = 0;
  var dupes = 0;
  lib_last = libSheet.getLastRow();
  while (sheet.getRange(x,1).getValue() != "") {
    if (sheet.getRange(x,5).getValue() != "") {
      id = sheet.getRange(x,1).getValue();
      var checkRow = checkDupes(id);
      if (checkRow >= lib_last + 1) {
        var my_name = DriveApp.getFileById(id).getName();
        SpreadsheetApp.getActiveSpreadsheet().toast('The design file: ' + '"' + my_name + '"' + ' has been added to the Library!', "ADDED FILE...",600);
        var my_link = DriveApp.getFileById(id).getUrl();
        getDeets(id, my_link);
        lib_last++;
        added++;
      } 
      else {
        dupes++;
      }
    }
    x++;
  }
  SpreadsheetApp.getActiveSpreadsheet().toast("", "",0.1);
  Browser.msgBox("Finished! Documents added: " + added + ". Duplicate documents: " + dupes);
  for (var i = x - 1; i>=2; i--) { // Deletes rows with non-null
    if (!sheet.getRange(i,5).isBlank()) {
      sheet.deleteRow(i);
    }
  }
}

回答1:

The cell being edited is being edited in the browser, not on the server. The request to update the value isn't sent to Google until the user stops editing. If users "stop" editing by clicking a button, then a race condition exists between which gets handled first - the script execution or the commit of the edit state.

I suggest using a custom script / add-on menu, which will cause the cell edits to be committed before the function can be invoked, because the browser selection changes from the spreadsheet cell to the Sheets menu bar.

function onOpen(e) {
  // add ons need to check authMode before doing this stuff
  e.source.addMenu('My Custom Menu', [
    { name: 'Add Selected Files to Library', functionName: 'addToLibrary' }
  ]);
}

Alternately:

function onOpen(e) {
  // add ons need to check authMode before doing this stuff
  SpreadsheetApp.getUi()
    .createMenu('My Custom Menu') // .createAddonMenu()
    .addItem('Add Selected Files to Library', 'addToLibrary')
    .addToUi();
}
  • Custom Menus
  • addMenu
  • Ui#Menu