首页 > 解决方案 > 如何将名称修改为上传的谷歌表单文件?

问题描述

我正在尝试使用以下脚本代码将名称修改为使用另一个文本从谷歌表单中的附件,我收到以下错误:

“ReferenceError:重命名时未定义 nameColumn(代码:26:22)”

我做错了什么?

var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
// Notice the second 2, this is to avoid the Timestamp Column
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);

// Replace with your values (Column A=1, B=2, etc...)
var nameColumn = 2; // B
var urlColumn = 3; // C

// Calculating index for array
nameColumn -= 2;
urlColumn -= 2;
}
function last() {
  var lastRowContents=sheet.getRange(lastRow,2,1,sheet.getLastColumn()).getValues()[0];
  rename(lastRowContents);
}
function rename(row) {

  // Using the first field, Name (Index 0 becuse of the array, calculated above)
  // ** Even though the Name field is the second column, we see it as the first one since 
  //    we ignored the timestamp column in the searchRange **
  var userName = row[nameColumn];
  var url = row[urlColumn];

  // Retrieve the ID from the URL
  var Id = url.split('=')[1];

  // Adapt this newFileName to your needs
  var newFileName = userName;

  // Get the file and rename it
  DriveApp.getFileById(Id).setName(newFileName);
  Logger.log("Renamed file with ID " + Id + " to " + newFileName);

};

标签: google-apps-scriptgoogle-sheetsgoogle-forms

解决方案


在表单的描述(https://developers.google.com/apps-script/reference/forms/item)中,我没有找到对附件的任何访问权限。我用一个问题创建了一个表格并插入了一张图片。我运行此代码以查看脚本是否可以访问图像。该脚本仅找到一项 - 未命名的问题。

function exploreFormItems() {
  const formId = '1EuPT6qNHfAWkbZhnlEpi1WPgMaIVPZDybM8h86jX3gg';
  let form = FormApp.openById(formId);
  let itemArr = form.getItems();
  let idx = 0;
  itemArr.forEach (function(item) {
    console.log ('idx     : ', idx );
    console.log ('   id   : ', item.getId() );
    console.log ('   index: ', item.getIndex() );
    console.log ('   title: ', item.getTitle() );
    console.log ('   type : ', item.getType() );
    console.log ('   help : ', item.getHelpText() );
    ++idx;
  }  );
}

如果您尝试重命名表单本身,我发现此https://stackoverflow.com/questions/47375841/how-to-change-a-file-name-of-a-google-form-b​​u -apps-script# :~:text=For%20a%20google%20电子表格%20it,重命名(%22new%20name%22)%3B


推荐阅读