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

Google Apps Script报错TypeError:无法读取undefined的属性'7'求助

问题分析与修复

报错原因

报错TypeError: Cannot read properties of undefined (reading '7')的核心问题是数组索引与表格行号不匹配:

  • Google Apps Script中,getDataRange().getValues()返回的二维数组是0索引,即表格第1行对应data[0],第2行对应data[1],以此类推。
  • 你的循环从i=2开始(对应表格第2行),当i等于表格最后行号lr时,data[i]超出了数组的最大索引(数组最大索引为lr-1),此时data[i]为undefined,访问[7]自然触发报错。
  • 另外,inform_cell = data[i][27]取的是单元格的值,不是Range对象,后续调用getValue()和setValue()还会触发新的错误。

修复后的代码

function sendEmailver2() {
  try{
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1");
    const data = sheet.getDataRange().getValues();
    const lr = data.length; // 用数组长度代替表格最后行号,避免索引混乱
    
    // 获取邮件模板
    const templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("template").getRange(1,1).getValue();

    // 从i=1开始(对应表格第2行数据),到i < lr结束(数组最后一个索引是lr-1)
    for(let i=1; i < lr; i++) {
      const rowNum = i + 1; // 转换为表格的1索引行号
      const CEO_box = sheet.getRange(rowNum, 25);
      const Acc_box = sheet.getRange(rowNum, 26);
      const inform_cell = sheet.getRange(rowNum, 28); // 第28列对应data[i][27],直接取Range对象
      
      // 从data数组中提取对应值
      const courseCol = data[i][7];
      const receiverName = data[i][6];
      const receiverEmail = data[i][18];
      const totalAmount = data[i][12];
      const informStatus = inform_cell.getValue();

      if(Acc_box.isChecked() && CEO_box.isChecked() && informStatus === "uninformed") {
        const subject = "please check email";
        const messageBody = templateText.replace("{name}", receiverName)
                                        .replace("{courseName}", courseCol)
                                        .replace("{amountVal}", totalAmount);
        console.log("send Email to:"+ receiverEmail);
        MailApp.sendEmail(receiverEmail, subject, messageBody);
        inform_cell.setValue("informed");
      }
    }
  } catch(e) {
    SpreadsheetApp.getUi().alert(e);
  }
}

关键修复点

  • 循环索引改为从i=1开始(对应表格第2行),条件改为i < lr(lr是数组长度,确保不越界)。
  • 新增rowNum = i + 1,统一转换为表格的1索引行号,避免行号与数组索引混淆。
  • inform_cell改为直接获取Range对象,而非从data数组取值,确保后续能正常调用getValue()和setValue()。
  • 用const替代不必要的var,提升代码可读性和安全性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:16:30