简体   繁体   中英

Dynamic Hyperlink based on cell contents in google sheets?

There is a list of items in a google spreadsheet, that we need to link a bunch of files from another folder on the google drive. The link is constructed with the function shown below:

function bscott () {

  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getActiveSheet();
  var c=s.getActiveCell();
  var fldr=DriveApp.getFolderById("**FOLDER ID - not included for security**");
  var files=fldr.getFiles();
  var names=[],f,str;

  while (files.hasNext()) {
    f=files.next();
    str='=hyperlink("' + f.getUrl() + '","' + f.getName() + '")';
    names.push([str]);
  }

  s.getRange(c.getRow(),c.getColumn(),names.length).setFormulas(names);
}

The problem we have encountered is if the contents of the folder do not match the ordering of our list exactly, the ordering of files to line items gets out of sync. We want certain files to hyperlink to certain cells in our sheet if the contents of another cell in the same row match the contents in the file name. We would like to avoid manually creating links for each line item. Is this possible in google sheets?

Create an object of file names to links:

var objNamesToLinks = {};//Create an empty object to be populated with data

Use your while loop to populate the object:

var fileName = "";//declare variable outside of the loop.

while (files.hasNext()) {
  f=files.next();
  fileName = f.getName();
  str='=hyperlink("' + f.getUrl() + '","' + fileName + '")';
  names.push([str]);

  objNamesToLinks[fileName] = str;//The object key is the file name
};

The result of the object will be:

objNamesToLinks = {
  'fileName1':'Link1',
  'fileName2':'Link2',
  'fileName3':'Link3'
};

Then get the column of data in your spreadsheet with the file names:

var columnWithFileNames = s.getRange(start Row, column with names, s.getLastRow())
    .getValues();

Then loop through the array of data in the column and match the file names up. If there is a match, look up the correct link, and put it into the cell.

var thisFileName, thisMatchedLink;

for (var i=0;i<columnWithFileNames.length;i+=1) {
  thisFileName = columnWithFileNames[i][0].trim();
  thisMatchedLink = objNamesToLinks[thisFileName];

  if (thisMatchedLink !== undefined) {
    s.getRange(i,columnToPutLinkInto).setValue(thisMatchedLink);
  };
}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM