Search code examples
google-apps-scriptgoogle-sheetsarray-formulascustom-function

How to use a custom function in an ARRAYFORMULA for a range of cells?


I have a Google Form that is populating a Google Sheet. Due to having custom formulas in the sheet to manipulate the data populated from the form I am using ARRAYFORMULA to apply to all rows in a column.

I have a custom function to encode rows containing html

function base64EncodeWebSafe(input) {

  try {
    // Try and fetch the specified url.
    return Utilities.base64EncodeWebSafe(input);

  } catch (e) { 
    Utilities.sleep(1000);
    return Utilities.base64EncodeWebSafe(input);

  }
}

When I call this function inside of ARRAYFORMULA(base64EncodeWebSafe(T2:T))

I receive an error "Cannot convert Array to (class)[]."

What I expect to happen is to apply the encoding function to the range T2:T


Solution

  • This is described in the Custom Functions guide. I've adapted the implementation used in the guide, but you could do something else. Basically, if using ARRAYFORMULA, then you need to treat the input as a 2-dimensional array.

    function base64EncodeWebSafe(input) {
      if (input.map) { // Test whether input is an array.
        return input.map(base64EncodeWebSafe)
      } else {
        try {
          return Utilities.base64EncodeWebSafe(input);
        } catch (e) {
          Utilities.sleep(1000);
          return Utilities.base64EncodeWebSafe(input);
        }
      }
    }