Add links to a cell in Google Sheets using Apps Script

In this tutorial, you'll learn how to add links into a cell in Google Sheets using Google Apps Script. When inserting links in cells, you have to decide whether all of the text in the cell should become a link or only a portion of the text.

To add links to a cell in Google Sheets using Apps Script, we need to first create a Rich Text Value and then apply this value to the cell's range.

The function linkCellContents() below inserts the link More information in cell Link!A2.

//OnlyCurrentDoc

function linkCellContents() {
 var range = SpreadsheetApp.getActive().getRange("Link!A2");
 var richValue = SpreadsheetApp.newRichTextValue()
   .setText("More information")
   .setLinkUrl("https://example.com")
   .build();
 range.setRichTextValue(richValue);
}

When you run the above function, a link will be inserted into cell A2.

Screenshot of a Google Sheets spreadsheet showing a cell containing a link.

You can also insert multiple links into a cell or link only a portion of the text by setting start and end offsets when configuring the link URL. When you set a start and end offset, only the text in between these positions will be linked.

The function insertMultipleLinksInCell() below inserts two links in the cell Link!A5 by specifying offsets. The resulting text has two links: article 1 which links to https://ex1.example.com and article 2 which links to https://ex2.example.com.

function insertMultipleLinksInCell() {
 var range = SpreadsheetApp.getActive().getRange("Link!A5");
 var richValue = SpreadsheetApp.newRichTextValue()
   .setText("For more information, see article 1 and article 2.")
   .setLinkUrl(26, 35, "https://ex1.example.com")
   .setLinkUrl(40, 49, "https://ex2.example.com")
   .build();
 range.setRichTextValue(richValue);
}
Screenshot of a Google Sheets spreadsheet showing a cell containing multiple links.

Conclusion

In this tutorial, you learned how to add links to a cell in Google Sheets using Google Apps Script. To add a link, you need to create a RichTextValue object and then set this value to the cell's range object. You can insert multiple links into a cell by specifying start and end offsets when setting the linkUrl() of the rich text value. Only the text in between these offsets will be linked.

Sign up to be notified when I publish new content

By signing up you agree to the Privacy Policy & Terms.