- There are the folder names and filenames on a sheet in the Spreadsheet.
- These folders and files are in the specific folder.
- Each name is the unique name in all values.
- You select the ranges. For example, it's "A1:D12" in the Spreadsheet of your image.
- You want to retrieve all file names and search the files using the filenames.
- You want to replace the retrieved values to the formulas of hyperlinks of the files.
From your replying and additional information, I could understand like above. If my understanding is correct, how about this sample script? Please think of this as just one of several possible answers.
Modified script:
After you set the folder ID, please select the range (for example, "A1:D12") and run the function of myFunction()
. By this, the filenames are replaced to the formulas of hyperlinks.
function myFunction() {
var folderId = "###"; // Please set the folder ID.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var c = s.getActiveRange()
var fldr = DriveApp.getFolderById(folderId);
var values = c.getValues();
var getFiles = function getFiles(folder) {
var folders = folder.getFolders();
while(folders.hasNext()) {
var fol = folders.next();
// for (var i = 0; i < values.length; i++) {
// for (var j = 0; j < values[i].length; j++) {
// values[i][j] = values[i][j] == fol.getName() ? ('=hyperlink("' + fol.getUrl() + '","' + fol.getName() + '")') : values[i][j];
// }
// }
getFiles(fol);
}
var files = folder.getFiles();
while (files.hasNext()) {
var f = files.next();
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[i].length; j++) {
values[i][j] = values[i][j] == f.getName() ? ('=hyperlink("' + f.getUrl() + '","' + f.getName() + '")') : values[i][j];
}
}
}
}(fldr);
if (values.length > 0) {
s.getRange(c.getRow(), c.getColumn(), values.length, values[0].length).setValues(values);
}
}
Note:
When the following lines, which are commented above, are used, the hyperlinks of folders are also put.
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[i].length; j++) {
values[i][j] = values[i][j] == fol.getName() ? ('=hyperlink("' + fol.getUrl() + '","' + fol.getName() + '")') : values[i][j];
}
}
If the same filenames and folder names are existing in the cell values and in subfolders, the logic for parsing the folders and files from the cell values is required. In your additional image, I cannot understand about the logic. This is due to my poor skill. I apologize for this.