Workaround: Retrieving Hyperlink from Cell of Number Value using Google Apps Script

Gists

This is a workaround for retrieving the hyperlink from the cell of a number value using Google Apps Script.

As a sample situation, it supposes that a cell “A1” has a number value like 123, and a hyperlink of https://tanaikech.github.io is set to the cell. In order to retrieve the hyperlink from the cell, it is required to use the methods of getRichTextValue() and getRichTextValues(). But, in the current stage, when the cell value is a number value, when the RichText is retrieved by getRichTextValue(), null is returned. By this, unfortunately, the hyperlink of the cell cannot be retrieved. This has already been reported in the Google issue tracker. Ref

In this post, I would like to introduce a workaround for retrieving hyperlinks from such cells.

Sample script:

function sample() {
  const srcRange = "Sheet1!A1:A10"; // Please set the source range.

  const range = SpreadsheetApp.getActiveSpreadsheet().getRange(srcRange);
  const orgNumberFormats = range.getNumberFormats();
  const values = range.setNumberFormat("@").getRichTextValues();
  const urls = values.map((r) => r.map((c) => c && (c.getLinkUrl(0, 1) || "")));
  range.setNumberFormats(orgNumberFormats);

  console.log(urls);
}

Reference

 Share!