Skip to content

Instantly share code, notes, and snippets.

@zacharysyoung
Last active April 18, 2025 17:58
Show Gist options
  • Save zacharysyoung/a5538015094b1caa02b2a594ec57a919 to your computer and use it in GitHub Desktop.
Save zacharysyoung/a5538015094b1caa02b2a594ec57a919 to your computer and use it in GitHub Desktop.
Insert Google Drive image links as =IMAGE(url) formula
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Insert images")
.addItem("Insert images", "insertImages")
.addToUi();
}
/**
* Scans the J-column of the current sheet, looking for
* Google Drive file links, getting the download URLs for
* each file, and then adding the download URL to an =IMAGE(url)
* formula in adjacent cells to the right of the J-column.
*/
function insertImages() {
// find and isolate the id chars from a the end of Google Drive file link
const reFileID = /.+id=(.+)/;
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const [startRowNo, j_ColNo] = [2, 10];
const lastRowNo = sheet.getLastRow() - startRowNo + 1; // +1 because 1-based row notation
const j_ColCells = sheet
.getRange(startRowNo, j_ColNo, lastRowNo, 1)
.getValues();
// iterate J-column cells
j_ColCells.forEach((cell, i) => {
const currentRowNo = startRowNo + i;
const links = cell[0].toString().split(",");
if (links.length === 0) {
console.error(`row ${currentRowNo}, emtpy links cell`);
return;
}
// iterate links
links.forEach((link, j) => {
j += 1; // 1-based column notation
const nextCol = j_ColNo + j;
const nextCell = sheet.getRange(currentRowNo, nextCol);
link = link.trim();
if (link === "") {
console.log(
`(row ${currentRowNo}, link ${j}) appears to be empty`,
);
return;
}
const m = link.match(reFileID); // m is a match object
if (!m || m.length !== 2) {
console.error(
`(row ${currentRowNo}, link ${j}) could not find "id=..." at end of "${link}"`,
);
return;
}
const fileID = m[1]; // the id submatch is in the 2nd field of the match object
const downloadURL = DriveApp.getFileById(fileID).getDownloadUrl();
if (nextCell.getFormula().includes(downloadURL)) {
console.log(
`(row ${currentRowNo}, link ${j}) already has the correct download URL, skipping`,
);
return;
}
const imageFormula = `=IMAGE("${downloadURL}")`;
nextCell.setFormula(imageFormula);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment