从单元格获取href超链接

问题描述 投票:0回答:1

我的单元格中有如下超链接:

我想从格式化的链接中提取真正的

href
链接。就像来自
google
真正的链接
www.google.com

我尝试使用以下功能:

function getCellLink(address) {

  if(!(address && typeof(address) == 'string'))
    throw new Error('The 1st param must be a cell address as a string.');

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cell = ss.getRange(address);
  var url = cell.getRichTextValue().getLinkUrl()

  if (!url) 
    throw new Error('The cell in ' + address + ' does not contain a link.');
  
  return url
}

但是,我仍然收到错误。

这是我的示例表的链接:

链接到示例电子表格

有什么建议我做错了什么吗?

感谢您的回复!

google-apps-script google-sheets google-sheets-formula
1个回答
1
投票

您引用的自定义函数需要将范围引用作为文本字符串。您可以通过插入引号来使公式起作用,如下所示:

=getCellLink("A2")

要一次性获得更多链接,请使用

RichTextLinks()
自定义函数,如下所示:

=RichTextLinks("A2:A4", A2:A4)

这是代码:

/**
* Retrieves addresses contained in rich text links.
*
* When rangeA1 is one column wide, returns each link separately, and the number of
* columns in the result range is determined by the max number of links per cell.
*
* When rangeA1 spans multiple columns, returns all links found in a cell as a
* comma-separated list.
*
* @param {"A2:A42"} rangeA1 A text string that specifies the cell range where to retrieve links.
* @param {A2:A42} dynamic_reference Optional. The same range as a normal range reference, to ensure that the results update dynamically.
* @return {String[][]} The addresses contained in rich text links.
* @customfunction
*/
function RichTextLinks(rangeA1, dynamic_reference) {
  // version 1.2, written by --Hyde, 13 April 2024
  let range;
  try {
    if (typeof rangeA1 !== 'string') throw new Error();
    range = SpreadsheetApp.getActiveSheet().getRange(rangeA1);
  } catch (error) {
    throw new Error(`RichTextLinks expected rangeA1 to be a text string like "A2:A42" but got the ${typeof rangeA1} "${rangeA1}" instead.`);
  }
  const richTextLinks = range.getRichTextValues().map(row => row.map(value =>
    value.getRuns().map(link => link.getLinkUrl()).filter(link => link)
  ));
  if (range.getWidth() === 1) {
    return richTextLinks.map(row => row[0]);
  }
  return richTextLinks.map(row => row.map(links => links.join(', ')));
}
© www.soinside.com 2019 - 2024. All rights reserved.