【问题标题】:Type error: cannot read property length from null类型错误:无法从 null 读取属性长度
【发布时间】:2019-04-27 11:01:40
【问题描述】:

我们有一张表格,用于获取工作质量表格的数据。这已经完美运行了一年多,从那时起,纸张、表格或脚本都没有任何改变。

但由于某种原因,现在每当我们运行 SendEmail 函数时都会出现错误:

TypeError: Cannot read property "length" from null. (line 83, file "SendEmail")

这是现在发生错误的地方:

for (var i = 0; i < templateVars.length; ++i) {

无论何时运行脚本,第一列(项目)都应自动输入序号。现在这一切都保持空白,并且电子邮件模板永远不会通过电子邮件发送。

function SendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheets()[0];
  var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 19);
  var lastRow = dataSheet.getMaxRows();
  for (var x = 0; x < dataSheet.getMaxRows() - 2; ++x) {
      if(dataSheet.getRange(x+2, 3).getValue()!=""){
        if(dataSheet.getRange(x+2, 15).getValue()==""){
             var EMInum = dataSheet.getRange((x + 1), 1).getValue() + 1;
             dataSheet.getRange(x+2, 1).setValue(EMInum);
             dataSheet.getRange(x+2, 2).setFormula("=\"QoW-\"&text(A" + (x+2) + ",\"000\")");
             dataSheet.getRange(x+2, 15).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,2,0)");
             dataSheet.getRange(x+2, 16).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,3,0)");
             dataSheet.getRange(x+2, 17).setFormula("=match(J" + (x+2) + ",CompanyName,1)");
             dataSheet.getRange(x+2, 18).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,Q" + (x+2) + ",0)");
             dataSheet.getRange(x+2, 19).setFormula("=vlookup(I" + (x+2) + ",ContactDetails,Q" + (x+2) + "+1,0)");
             dataSheet.getRange(x+2, 27).setFormula("=I" + (x+2)+ "&if(Z" + (x+2)+ "=\"\" ,\" OPEN\",\" CLOSED\")");
             dataSheet.getRange(x+2, 28).setFormula("=if(right(AA" + (x+2) + ",4)=\"OPEN\",now()-datevalue(I" + (x+2)+ "),0)");
             dataSheet.getRange(x+2, 29).setFormula("=if(AB" + (x+2) + "=0,\"e) Closed\",if(AB" + (x+2) + "<90,\"a) 0 - 90 days\",if(AB" + (x+2) + "<180,\"b) 90 - 180 days\",if(AB" + (x+2) + "<360,\"c) 180 - 360 days\",\"d) Over 360 days\"))))");
             //Browser.msgBox("");
          }
        }
      }  

  //


  //


  var templateSheet = ss.getSheets()[1];
  var emailTemplate = templateSheet.getRange("A1").getValue();
  var defaultCCAddress = templateSheet.getRange("B17").getValue(); // Added by zumzum as per projectid:a0CD000000xFxWQ

  // Create one JavaScript object per row of data.
  objects = getRowsData(dataSheet, dataRange);

  // For every row object, create a personalized email from a template and send
  // it to the appropriate person.
  for (var i = 0; i < objects.length; ++i) {
    // Get a row object
    var rowData = objects[i];

    // Generate a personalized email.
    // Given a template string, replace markers (for instance ${"First Name"}) with
    // the corresponding value in a row object (for instance rowData.firstName).
    var emailText = fillInTemplateFromObject(emailTemplate, rowData);
    var emailSubject = "NO REPLY: EM&I Quality of Work Issue Submission " + dataSheet.getRange(i + 2, 2).getValue();
    var emailCheck = dataSheet.getRange(i + 2, 13).getValue();
    //Browser.msgBox(emailCheck);
    var emailAddress = dataSheet.getRange(i + 2, 18).getValue();
    var ccemailAddress = dataSheet.getRange(i + 2, 15).getValue();
    if(emailCheck=="")
    {
      /* original code commented by zumzum as per projectid:a0CD000000xFxWQ
      MailApp.sendEmail(emailAddress, emailSubject, emailText,{cc:ccemailAddress+",david.mortlock@emialliance.com,peter.gresty@emialliance.com",bcc:"richard.priddes@emialliance.com"});
      dataSheet.getRange(i + 2, 13).setValue("sent - " + Date());
      */
      // Start od new code added by zumzum as per projectid:a0CD000000xFxWQ
      MailApp.sendEmail(emailAddress, emailSubject, emailText,{cc:ccemailAddress+","+defaultCCAddress}); 
      dataSheet.getRange(i + 2, 13).setValue("sent - " + Date()); 
      // End of new code added by zumzum as per projectid:a0CD000000xFxWQ
    }   
  }
}


// Replaces markers in a template string with values define in a JavaScript data object.
// Arguments:
//   - template: string containing markers, for instance ${"Column name"}
//   - data: JavaScript object with values to that will replace markers. For instance
//           data.columnName will replace marker ${"Column name"}
// Returns a string without markers. If no data is found to replace a marker, it is
// simply removed.
function fillInTemplateFromObject(template, data) {
  var email = template;
  // Search for all the variables to be replaced, for instance ${"Column name"}
  var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);

  // Replace variables from the template with the actual values from the data object.
  // If no value is available, replace with the empty string.
  for (var i = 1; i < templateVars.length; i++) {
    // normalizeHeader ignores ${"} so we can call it directly here.
    var variableData = data[normalizeHeader(templateVars[i])];
    email = email.replace(templateVars[i], variableData || "");
  }

  return email;
}





//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial.
//
//////////////////////////////////////////////////////////////////////////////////////////

// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
//   - sheet: the sheet object that contains the data to be processed
//   - range: the exact range of cells where the data is stored
//   - columnHeadersRowIndex: specifies the row number where the column names are stored.
//       This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
  columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
  var numColumns = range.getEndColumn() - range.getColumn() + 1;
  var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(range.getValues(), normalizeHeaders(headers));
}

// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
//   - data: JavaScript 2d array
//   - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
  var objects = [];
  for (var i = 0; i < data.length; ++i) {
    var object = {};
    var hasData = false;
    for (var j = 0; j < data[i].length; ++j) {
      var cellData = data[i][j];
      if (isCellEmpty(cellData)) {
        continue;
      }
      object[keys[j]] = cellData;
      hasData = true;
    }
    if (hasData) {
      objects.push(object);
    }
  }
  return objects;
}

// Returns an Array of normalized Strings.
// Arguments:
//   - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
//   - header: string to normalize
// Examples:
//   "First Name" -> "firstName"
//   "Market Cap (millions) -> "marketCapMillions
//   "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    if (!isAlnum(letter)) {
      continue;
    }
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

// Returns true if the cell where cellData was read from is empty.
// Arguments:
//   - cellData: string
function isCellEmpty(cellData) {
  return typeof(cellData) == "string" && cellData == "";
}

// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
  return char >= 'A' && char <= 'Z' ||
    char >= 'a' && char <= 'z' ||
    isDigit(char);
}

// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
  return char >= '0' && char <= '9';
}```

【问题讨论】:

  • 我们需要看看templateVars 被分配到什么,因为那是null。我们还需要知道创建序列号的原因是什么:它是脚本函数,还是单元格中可能有人意外删除的 Sheets 函数?
  • 您好。是的,它是创建序列号的脚本函数。我如何查看模板变量是什么或分配给什么?
  • 您能否在您的问题中添加更多代码(或所有代码)?我们没有足够的信息。如果您发布所有代码,我们可以指出 templateVars 分配给什么。见stackoverflow.com/help/mcve
  • 已添加完整代码。请忽略代码顶部缺少的函数,它存在但无法在此处的代码中获取。
  • 按照此处详述的步骤操作:minimal reproducible example

标签: google-apps-script


【解决方案1】:

您遇到的错误可以通过运行fillInTemplateFromObject(emailTemplate, rowData)emailTemplate 的任何不包含${"foo"} 形式的占位符的字符串来重现(每个正则表达式/\$\{\"[^\"]+\"\}/g 都需要文字双引号)。

SendEmail 中,emailTemplate 的值来自第一个工作表单元格 A1。检查您在该单元格中的值。它是否包含正确的${"foo"} 形式的模板?

由于此错误可能是由用户操作电子表格引起的,因此请考虑通过在尝试使用预期数组之前检查成功的 match 来改进 fillInTemplateFromObject

function fillInTemplateFromObject(template, data) {
  var email = template;
  // Search for all the variables to be replaced, for instance ${"Column name"}
  var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
  if (! templateVars) {
    throw new Error("No templates found in your template sheet.  Aborting.")
  }
  // Replace variables from the template with the actual values from the data object.
  // If no value is available, replace with the empty string.
  for (var i = 0; i < templateVars.length; i++) {
    // normalizeHeader ignores ${"} so we can call it directly here.
    var variableData = data[normalizeHeader(templateVars[i])];
    email = email.replace(templateVars[i], variableData || "");
  }

  return email;
}

您可以在 SendEmail 中发现该错误并提供更多有用的信息:

// inside SendEmail
try {
  var emailText = fillInTemplateFromObject(emailTemplate, rowData);
} catch (error) {
  throw new Error("In spreadsheet " + ss.getUrl() + " sheet " + templateSheet.getSheetName() + " row " + (i+1) + " there were no templates found.")
}

如果您仍然需要帮助调试错误,use the apps script debugger 或使用various logging options built into apps script 在运行时输出数据的状态。

【讨论】:

    【解决方案2】:

    为什么你使用 ++i 而不是 i++?我的猜测是这就是问题所在,如果 templateVars 是一个数组,那么您将到达数组的末尾并尝试在不存在的行上运行一次。也许以前,这是一个空行,但现在最后一行是工作表的末尾。

    我对你的代码一无所知:

    for (var i = 0; i < templateVars.length; ++i) {
    

    for (var i = 1; i < templateVars.length; i++) {
    

    【讨论】:

    • 嗨,J.G.非常感谢。我尝试了这种改变,但它仍然给我同样的错误。 // 用 Ja​​vaScript 数据对象中定义的值替换模板字符串中的标记。 // 参数: // - 模板:包含标记的字符串,例如 ${"Column name"} // - 数据:具有值的 JavaScript 对象将替换标记。例如 // data.columnName 将替换标记 ${"Column name"} // 返回一个不带标记的字符串。如果没有找到替换标记的数据,则 // 简单地删除它。 function fillInTemplateFromObject(template, data) { var email = template;
    • @Paul Zumzum 您应该将此代码放入您的问题中。您是否有可能没有在输入中使用任何${"template"}?这或许可以解释为什么 templateVars 为空。
    • 已添加完整代码。请忽略顶部缺少的函数,它存在但无法在此处的代码中获取。
    猜你喜欢
    • 2014-11-18
    • 2012-10-11
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2021-12-03
    • 2023-01-31
    相关资源
    最近更新 更多