google-apps-scriptgoogle-sheetsrtfrichtext

Can't log richtext string of a cell because of data validation?


My cell F394 looks like this:

08/10/2023 And there is a link attached to it (not as hyperlink, but as RichText).

Data validation is active and allows for short date only in exactly this format (dd/mm/yyyy).

I want to obtain/log the URL that's attached via a script:

function logURLToCloudLogs() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cell = sheet.getRange("F394"); 
  var richTextValue = cell.getRichTextValue();

  for (var i = 0; i < richTextValue.getTextRuns().length; i++) {
    var textRun = richTextValue.getTextRuns()[i];
    if (textRun.getLinkUrl()) {
      var linkUrl = textRun.getLinkUrl();
      Logger.log("URL:" + linkUrl);
      return;
    }
  }

  Logger.log("Cell contains no URL.");
}

But it results in error:

TypeError: Cannot read properties of null (reading 'getTextRuns') logURLToCloudLogs @ ShowDateEdit.gs:7

When I log the value of the cell via .getValue(), i get:

Sun Oct 08 00:00:00 GMT+02:00 2023

My suspicion is that, due to the data validation, apps script does not identify the string as richtext.

Can anyone help me successfully log the richtext & obtain the URL?


Solution

  • Modification points:

    In this case, when your showing script is modified, how about the following modification?

    Modified script:

    function logURLToCloudLogs() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var cell = sheet.getRange("F394"); 
      var orgNumberFormats = cell.getNumberFormats();
      cell.setNumberFormat("@");
      var richTextValue = cell.getRichTextValue();
      cell.setNumberFormats(orgNumberFormats);
      var runs = richTextValue.getRuns();
      for (var i = 0; i < runs.length; i++) {
        var textRun = runs[i];
        if (textRun.getLinkUrl()) {
          var linkUrl = textRun.getLinkUrl();
          Logger.log("URL:" + linkUrl);
          return;
        }
      }
      Logger.log("Cell contains no URL.");
    }
    

    Note:

    References: