You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets无法识别自定义脚本函数distance的问题求助

解决Google Sheets自定义函数无法被识别的问题

嘿,作为Google Apps Script新手,这个问题其实很常见——你的函数缺少返回值,这就是Sheets找不到它或者无法正常工作的核心原因!

问题分析

Google Sheets的自定义函数必须通过return语句把计算结果返回给单元格,否则表格无法识别这个函数的输出,自然在输入=时也不会正常显示它。看你的代码,最后已经计算出了距离的米数meters,但没有把这个值返回出去。

修复后的代码

function distance(origin, destination) {
  var mapObj = Maps.newDirectionFinder();
  mapObj.setMode(Maps.DirectionFinder.Mode.DRIVING);
  mapObj.setOrigin(origin);
  mapObj.setDestination(destination);
  var directions = mapObj.getDirections();
  var meters = directions["routes"][0]["legs"][0]["distance"]["value"];
  // 关键:添加返回语句,把计算结果返回给单元格
  return meters; // 如果需要公里数,可以改成 return meters / 1000;
}

额外注意事项

  • 授权验证:第一次在表格中调用这个函数时,会弹出授权提示,你需要按照步骤完成授权(因为函数调用了Maps服务,需要获取相应权限)。
  • 参数格式:确保传入的origin和destination是有效的地址字符串(比如"北京天安门"),或者引用包含地址的单元格(比如=distance(A1, B1),其中A1和B1分别存出发地和目的地)。
  • 错误处理:如果地址无效或者无法获取路线,当前代码会报错,你可以添加简单的错误处理,比如:
    function distance(origin, destination) {
      try {
        var mapObj = Maps.newDirectionFinder();
        mapObj.setMode(Maps.DirectionFinder.Mode.DRIVING);
        mapObj.setOrigin(origin);
        mapObj.setDestination(destination);
        var directions = mapObj.getDirections();
        var meters = directions["routes"][0]["legs"][0]["distance"]["value"];
        return meters;
      } catch (e) {
        return "无法获取路线,请检查地址是否正确";
      }
    }
    

内容的提问来源于stack exchange,提问作者Clemente Chiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:50:53