Google App脚本 - 将文件复制到名称范围内的文件夹中

时间:2017-03-01 00:03:56

标签: google-apps-script google-sheets google-apps

我正在Google表格中工作,我正在尝试创建一个脚本,该脚本将生成当前文件的一定数量的副本,从而为每个副本提供一个范围内的名称列表中的下一个名称,并将这些文件放在由以前的脚本创建的文件夹中。我能够完成所有工作,但仅限于第一个文件(6个中,可能更多)并且无法弄清楚我做错了什么。 Here's a copy of the sheet。我还有另一个版本,只能创建文档的副本,但我试图简化最终用户的流程,可能会创建数十个副本,并希望为他们组织这些工作会有所帮助

感谢您的帮助!

这是脚本:

function createcopies2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();

// Get the range of cells that store necessary data.
var CoachNames = ss.getRangeByName("CoachNames");

var CoachObjects = CoachNames.getValues();

var schoolNames = ss.getRangeByName("SchoolNames");

var SchoolObjects = schoolNames.getValues();

var id = ss.getId();  
// The next variable gets a value that counts how many CoachNames there are in the spreadsheet
var coaches = ss.getRangeByName("Coaches");

var numcoaches = coaches.getValue();

//here's the function
for(i=0; i<numcoaches; i++){ 

var drive=DriveApp.getFileById(id);

var name=CoachObjects[i].toString();

var folder=DriveApp.getFoldersByName(SchoolObjects[i]).next();

var folderid=folder.getId();

var folder2=DriveApp.getFolderById(folderid)
if(folder) {
drive.makeCopy(name, folder2)}
else{
drive.makeCopy(name);
}

return;
}
}

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。 我在下面修改了你的解释:

function createcopies2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();

// Get the range of cells that store necessary data.
var CoachNames = ss.getRangeByName("CoachNames");
//The below statements a 2D dimensional array.
//To access the individual value you will have a statement like this
//CoachObjects[0][0],CoachObject[1][0],[2][0] ..., down the row
var CoachObjects = CoachNames.getValues();

var schoolNames = ss.getRangeByName("SchoolNames");
//The below statements a 2D dimensional array.
var SchoolObjects = schoolNames.getValues();

var id = ss.getId();  
// The next variable gets a value that counts how many CoachNames there are in the spreadsheet
var coaches = ss.getRangeByName("Coaches");

var numcoaches = coaches.getValue();
//Moved the below statement out of the loop
// Baceause you are using the same file
var drive=DriveApp.getFileById(id);
//here's the function
for(i=0; i<numcoaches; i++){ 
var name=CoachObjects[i][0].toString();

var folder=DriveApp.getFoldersByName(SchoolObjects[i][0]).next();

var folderid=folder.getId();

var folder2=DriveApp.getFolderById(folderid)
if(folder) {
drive.makeCopy(name, folder2)}
else{
drive.makeCopy(name);
}

return;
}
}

我修改了代码,因为你从getValues

获得了一个2D数组
//The below statements a 2D dimensional array.

var CoachObjects = CoachNames.getValues();

要访问单个值,您将使用类似这样的语句

`CoachObjects[0][0]`
 CoachObjects[1][0]
 .......     [2][0] ...
 down the row

此外,这些是冗余的代码行:

var folder=DriveApp.getFoldersByName(SchoolObjects[i][0]).next();
var folderid=folder.getId();
var folder2=DriveApp.getFolderById(folderid)

你可以用

替换它
var folder2=DriveApp.getFoldersByName(SchoolObjects[i][0]).next();