使用自定义MD5公式与ARRAYFORMULA

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

我实现了这里提到的MD5公式:Hash of a cell text in Google Spreadsheet

function MD5 (input) {
  var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
  Utilities.sleep(100)
  var txtHash = '';
  for (i = 0; i < rawHash.length; i++) {
    var hashVal = rawHash[i];
    if (hashVal < 0) {
      hashVal += 256;
    }
    if (hashVal.toString(16).length == 1) {
      txtHash += '0';
    }
    txtHash += hashVal.toString(16);
  }
  return txtHash;
}

现在我想用ARRAYFORMULA运行它,但我不能让它工作。我试过这个:

=ARRAYFORMULA(({"FiBu MD5";IF(ISBLANK(AG2:AG),"",(MD5(O2:O)))}))

我得到的错误是:

“无法将数组转换为(类)[]。(第2行)。”

有谁知道如何解决这个问题?

google-apps-script google-sheets md5 spreadsheet array-formulas
1个回答
0
投票

这个修改怎么样?

例如,当使用你的问题的当前脚本时,在MD5(O2:O)用作自定义函数的情况下,inputfunction MD5(input) {}是像[[value of O2], [value of O3],,,]这样的2维数组。但是在您的脚本中,通过输入不是数组的值来返回结果。这样,就会出现问题中显示的错误。因此,为了输入和输出数组,需要针对这种情况修改脚本,如下所示。

Modified script:

function MD5(input) {
  for (var i = input.length - 1; i >= 0; i--) {
    if (input[i][0]) {
      input.splice(i + 1);
      break;
    }
  }
  var result = input.map(function(e) {
    if (e[0] != "") {
      var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, e[0]);
  //    Utilities.sleep(100) // I thought that this might be not required.
      var txtHash = '';
      for (i = 0; i < rawHash.length; i++) {
        var hashVal = rawHash[i];
        if (hashVal < 0) {
          hashVal += 256;
        }
        if (hashVal.toString(16).length == 1) {
          txtHash += '0';
        }
        txtHash += hashVal.toString(16);
      }
      return [txtHash];
    }
    return [];
  });
  return result;
}

Note:

  • 我认为通过上面的修改,你也可以使用={"FiBu MD5";MD5(O2:O)}的公式代替=ARRAYFORMULA(({"FiBu MD5";IF(ISBLANK(AG2:AG),"",(MD5(O2:O)))}))

如果这不起作用,我道歉。那时,为了正确理解你的情况,你能提供样本电子表格吗?通过这个,我想修改脚本。

© www.soinside.com 2019 - 2024. All rights reserved.