我正在嘗試更改我在本網站上找到的一些代碼,使其更適合我的專案,并對我的同事更用戶友好。
我正在嘗試從電子表格中的單元格中提取源檔案夾和目標檔案夾的檔案夾 ID。我很確定我為這部分正確執行了代碼,但是在嘗試運行代碼時出現 ID 例外錯誤。當我直接將 ID 放入代碼中時,使用引號使它們成為字串,我目前擁有 resSource 和 resTarget,代碼完美運行。
我不知道如何使用變數將檔案夾 ID 正確傳遞到函式中……有人可以幫忙嗎?
function onOpen(){
createMenu()
}
function createMenu (){
const ui = SpreadsheetApp.getUi()
const menu = ui.createMenu("Copy Folders")
menu.addItem("Copy Folder", "copyFolder")
menu.addToUi()
}
/**
* Copies all the files in a folder to another one.
*/
function copyFolderContents_(source, target) {
// Iterate files in source folder
const filesIterator = source.getFiles()
while (filesIterator.hasNext()) {
const file = filesIterator.next()
// Make a copy of the file keeping the same name
file.makeCopy(file.getName(), target)
}
}
/**
* Recursivelly copies a folder and all its subfolders with all the files
*/
function copyFolder_(toCopy, copyInto) {
// Makes the new folder (with the same name) into the `copyInto`
const newFolder = copyInto.createFolder(toCopy.getName())
// Copy the contents
copyFolderContents_(toCopy, newFolder)
// Iterate any subfolder
const foldersIterator = toCopy.getFolders()
while (foldersIterator.hasNext()) {
const folder = foldersIterator.next()
// Copy the folder and it's contents (recursive call)
copyFolder_(folder, newFolder)
}
}
/**
* Entry point to execute with the Google Apps Script UI
*/
function copyFolder() {
// Get the folders (by ID in this case)
const toCopy = DriveApp.getFolderById(resSource)
const copyInto = DriveApp.getFolderById(resTarget)
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
var sourceText = activeSheet.getRange("A2").getValue();
var resSource = sourceText.toString;
console.log(resSource);
var targetText = activeSheet.getRange("B2").getValue();
var resTarget = targetText.toString;
console.log(resTarget);
// Call the function that copies the folder
copyFolder_(toCopy, copyInto)
}
uj5u.com熱心網友回復:
function copyFolderContents_(source, target) {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("SheetName");
const vs = sh.getRange(2, 1, sh.getLastRow() - 1, 2).getValues();
vs.forEach(r => {
let source = DriveApp.getFolderById(r[0]);
let target = DriveApp.getFolderById(r[1]);
const files = source.getFiles()
while (files.hasNext()) {
const file = files.next()
file.makeCopy(file.getName(), target)
}
});
}
| 一種 | 乙 |
|---|---|
| 來源 ID | 目標 ID |
uj5u.com熱心網友回復:
在 copyFolder 函式上,代碼正在傳遞resSource并resTarget作為幾個陳述句的引數,但這些變數是在它們之后宣告的。
嘗試移動
// Get the folders (by ID in this case)
const toCopy = DriveApp.getFolderById(resSource)
const copyInto = DriveApp.getFolderById(resTarget)
就在之前
// Call the function that copies the folder
copyFolder_(toCopy, copyInto)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334409.html
