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

运行谷歌表格邮件发送脚本时遇getDataRange空值读取错误求助

错误「Cannot read properties of null (reading 'getDataRange')」原因分析

问题背景

我使用的Google Apps Script脚本用于按谷歌表格每行数据发送邮件,运行时触发上述错误,相关代码如下:

/**
 * Returns a rectangular grid of values in a given sheet.
 * @param {string} sheetName The name of the sheet.
 * @return {object[][]} A two-dimensional array of values in the sheet.
 */
function getData(sheetName) {
  var data = SpreadsheetApp.getActive().getSheetByName(sheetName).getDataRange().getValues();
  return data;
}

/**
 * Sends an email for each row.
 */
function sendEmails() {
  var templateData = getData("Templates");
  var emailSubject = templateData[1][0]; //Cell A2 (contains the email subject)
  var emailBody = templateData[4][0]; //Cell A5 (contains the email body)
  var emailData = getData("Emails");
  var headerRow = emailData.shift(); //Remove the header row
  emailData.forEach(function (row) {
    var email = row[0];
    MailApp.sendEmail(email, emailSubject, emailBody);
  });
}

错误原因

这个错误本质是getSheetByName(sheetName)返回了null(即脚本找不到指定名称的工作表),后续调用getDataRange()时因null没有该属性而报错,具体可能的触发场景:

  • 工作表名称不匹配:检查表格中是否存在Templates和Emails工作表,注意大小写、空格、特殊字符必须完全一致,比如把Templates写成Template、emails全小写都会导致找不到。
  • 工作表状态变更:目标工作表被删除、重命名,或者移到了其他谷歌表格中,脚本里的名称未同步更新。
  • 激活表格错误:SpreadsheetApp.getActive()获取的是当前打开的表格,如果你在其他表格中运行该脚本,自然找不到目标工作表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:25:02