Search code examples
google-apps-scriptgoogle-sheetstriggersgoogle-drive-api

Rename the value of a file according to value of a cell inside a spreadsheet


Basically is I have a sheet which control de name of other files :

Inside "source sheet" I have the cells in column A, which I put new names and cells in columns B, which contains the ID of the files I want to rename :

What I want is : each time I edit the names cell in column A, the file which belong to the ID chage the name, I mean rename.

To do this, I am implementing a Script in Google App Script which is the following:

This is the code :

function onEdit(e) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var edited_range = e.range;
  var edited_row = edited_range.getRow();
  var newName = spreadsheet.getActiveSheet().getRange(edited_row,1).getValue();
  var idDeBox = spreadsheet.getActiveSheet().getRange(edited_row,2).getValue();
  var file = SpreadsheetApp.openById(idDeBox);
  file.rename(newName);
}

But It doesn't work. It doesn't rename the files. I am struggling with this. What am I doing wrong ?

Update : I get this from execution logs :

enter image description here


Solution

  • Try it like this:

    Note: you are not actually specifying what cell you are actually editing.

    function renameFile(e) {
      const sh = e.range.getSheet();
      var newName = sh.getRange(e.range.rowStart,1).getValue();
      var idDeBox = sh.getRange(e.range.rowStart,2).getValue();
      var file = SpreadsheetApp.openById(idDeBox);
      file.rename(newName);
    }
    

    and create an installable onEdit trigger with name of renameFile