The built-in SpreadsheetApp service doesn't seem to support pulling such URLs out, but the “Advanced” Sheets service does.
Enable the Advanced Sheets service according to Google's instructions, and then try this code:
function onOpen() {
var menu = SpreadsheetApp.getUi().createMenu("Extract URLs");
menu.addItem("Process =EXTRACT_URL(A1) formulas", "processFormulas");
menu.addToUi();
}
function EXTRACT_URL() {
return SpreadsheetApp.getActiveRange().getFormula();
}
function processFormulas() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var rows = sheet.getDataRange().getFormulas();
for (var r = 0; r < rows.length; r++) {
var row = rows[r];
for (var c = 0; c < row.length; c++) {
var formula = row[c];
if (formula) {
var matched = formula.match(/^=EXTRACT_URL\((.*)\)$/i);
if (matched) {
var targetRange = matched[1];
if (targetRange.indexOf("!") < 0) {
targetRange = sheet.getName() + "!" + targetRange;
}
var result = Sheets.Spreadsheets.get(spreadsheet.getId(), {
ranges: targetRange,
fields: 'sheets.data.rowData.values.hyperlink'
});
try {
var value = result.sheets[0].data[0].rowData[0].values[0].hyperlink;
sheet.getRange(r + 1, c + 1).setValue(value);
} catch (e) {
// no hyperlink; just ignore
}
}
}
}
}
}
This creates a custom function called EXTRACT_URL
, which you should call with a reference to the cell that contains the link; for example, =EXTRACT_URL(B3)
.
Unfortunately it doesn't work immediately, because the Advanced Sheets service can't be used directly by custom functions. So this script adds a menu called “Extract URLs” to the spreadsheet menu bar, with one menu item labeled “Process =EXTRACT_URL(A1) formulas”. When you click it, it will replace all uses of the EXTRACT_URL
function with the URL itself.