如何在Google Sheets中提取HYPERLINK内URL并解决代码报错问题?
解决Google Sheets提取超链接URL的问题
错误原因说明
你遇到的Error Attempted to execute GETLINKmenu, but it was deleted.错误,和当前用的提取代码无关——大概率是你的表格里还留着绑定了已删除函数(比如GETLINKmenu)的按钮、宏或者快捷键,只要清理掉这些无效绑定就能消除这个报错。
修复并优化你的提取代码
你提供的代码只处理了=HYPERLINK()公式生成的超链接,漏掉了手动插入的超链接(就是单元格文本直接带跳转的那种),还有拼写错误spreadsheedId应该是spreadsheetId。下面是修复后能提取所有类型超链接的版本,还会把结果直接输出到新工作表里,比日志更直观:
const extractAllHyperlinks = () => { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = SpreadsheetApp.getActiveSheet(); const dataRange = sheet.getDataRange(); const values = dataRange.getDisplayValues(); const hyperlinks = []; const spreadsheetId = ss.getId(); const sheetName = sheet.getName(); // 获取单元格的A1格式地址 const getA1Notation = (row, col) => { return `${sheetName}!${sheet.getRange(row + 1, col + 1).getA1Notation()}`; }; // 调用Sheets API获取超链接数据 const fetchHyperlink = (rowIndex, colIndex) => { try { const response = Sheets.Spreadsheets.get(spreadsheetId, { ranges: [getA1Notation(rowIndex, colIndex)], fields: 'sheets(data(rowData(values(formattedValue,hyperlink))))' }); const cellData = response.sheets[0]?.data[0]?.rowData[0]?.values[0]; if (cellData?.hyperlink) { hyperlinks.push({ 行号: rowIndex + 1, 列号: colIndex + 1, 显示文本: cellData.formattedValue || values[rowIndex][colIndex], URL: cellData.hyperlink }); } } catch (e) { console.log(`单元格(${rowIndex+1}, ${colIndex+1})提取失败: ${e.message}`); } }; // 遍历所有单元格,检测公式和手动插入的超链接 dataRange.getRichTextValues().forEach((row, rowIndex) => { row.forEach((cell, colIndex) => { // 检查手动插入的超链接 const hasManualLink = cell.getRuns().some(run => run.getLinkUrl() !== null); // 检查HYPERLINK公式 const hasFormulaLink = /=HYPERLINK/i.test(dataRange.getFormulas()[rowIndex][colIndex]); if (hasManualLink || hasFormulaLink) { fetchHyperlink(rowIndex, colIndex); } }); }); // 输出结果到新工作表 if (hyperlinks.length > 0) { const resultSheet = ss.getSheetByName("超链接提取结果") || ss.insertSheet("超链接提取结果"); resultSheet.clear(); // 写入表头 resultSheet.getRange(1, 1, 1, 4).setValues([["行号", "列号", "显示文本", "URL"]]); // 写入提取到的数据 const outputData = hyperlinks.map(item => [item.行号, item.列号, item.显示文本, item.URL]); resultSheet.getRange(2, 1, outputData.length, 4).setValues(outputData); SpreadsheetApp.getUi().alert(`成功提取${hyperlinks.length}个超链接,结果已写入"超链接提取结果"工作表`); } else { SpreadsheetApp.getUi().alert("未找到任何超链接"); } };
使用步骤
- 打开你的Google Sheets,点击顶部菜单「扩展程序」→「Apps脚本」进入脚本编辑器。
- 删除原有代码,粘贴上面的优化版代码。
- 点击编辑器顶部的「运行」按钮,首次运行会弹出授权请求,按照提示完成授权(需要信任这个脚本)。
- 运行完成后,表格会自动生成「超链接提取结果」工作表,所有超链接信息都在里面。
额外注意点
- 如果遇到权限问题,进入脚本编辑器的「编辑器」→「项目设置」,勾选「显示"appsscript.json"清单文件」,打开该文件确保
oauthScopes包含以下内容:"oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.external_request" ] - 清理无效绑定:检查表格里是否有插入的按钮(右键按钮→「分配脚本」,如果脚本名是GETLINKmenu就删除绑定),或者进入「扩展程序」→「宏」,删掉失效的宏。
内容的提问来源于stack exchange,提问作者Ranjan Kumar Singh
相关产品推荐
相关产品推荐

