0

これはパズルです。私はGoogleスプレッドシートを持っています。講義のオンライン評価を許可するという意味です。居住者は関連するフォームにログインし、記入します。

これに付随するのが「ナグ」機能です。2 番目のシートは名前をチェックし、提出済みかどうかを追跡し、提出していない場合は一定時間 (3 日) が経過するとナグ メールを送信します。

手動で実行すると、スクリプトは正常に実行されます。また、分タイマーを使用する場合 (つまり、10 分ごとに実行)。

しかし、1 日に 1 回チェックするようにスクリプトをセットアップすると、実行されず、次のエラー レポートが表示されます。

無効なメール: #N/A

他のスプレッドシートで他の同様の関数を実行していて、常に機能しているため、これは特に奇妙です。

ここで私が考えることができる唯一の違いは、いくつかの同様のスクリプトを実行していることです (毎週 1 つのシート)。関数名を一意のものに変更し、スプレッドシートの呼び出しを openById に変更し、シート変数を getSheetByName に変更して、複数の同様のスクリプトが何らかの形で互いに混乱した場合に備えました。違いはありません。

スプレッドシートのコピーへのリンクはこちらhttps://docs.google.com/a/brown.edu/spreadsheet/ccc?key=0AkP6szc0nsS2dEItLXEwdjVsWUFpOTdjZUdtTlo4cGc#gid=0

以下にスクリプトを添付します (エラー報告を追加したことにお気付きでしょうが、あまり追加されていません)。データ変数はチュートリアルから借用しており、そのチュートリアルのスニペットは常にうまく機能しています。

任意の洞察をいただければ幸いです。

コード:

var SEMINAR_FORM_URL = "http://med.brown.edu/DPHB/training/psychiatry_general/secure/seminarevals/seminar_evals.html";
var YES = "YES";
var DISTRIBUTE = "robert_boland_1@brown.edu,robertboland11@gmail.com"; 

//This function sends out a nag to do the seminar evals including a link to the seminar form
//This is allowed when sheet 2 says "YES" to "Nag?"  
//Should not check more than once daily or will keep sending out and should be triggered AFTER the checkCoverageSubmit. 

function sendNag() {  
  try {
  var ss = SpreadsheetApp.openById("0AkP6szc0nsS2dDkwQTE0OVlPeWM5ZlJIenVKLU1pVVE");
  var sheet = ss.getSheetByName("Sheet2");
  var startRow = 2

  // getRowsData was reused from Reading Spreadsheet Data using JavaScript Objects tutorial
  var data = getRowsData(sheet);

  // For every Seminar report row
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    row.rowNumber = i + 2;    
    if (row.nag==YES) {   //sends the nag message below
     var message = "<HTML><BODY>"
    + "<P> THIS IS A REMINDER MESSAGE:"
    + "<P> For "  + row.name         
    + "<P> You still need to complete your seminar evaluations for" 
    + "<P> the seminars done on "+ row.dateOfSeminar
    + "<P>" 
    + "<P> It has been "+ row.daysElapsed + " days since the seminar." 
    + "<P>"     
    + '<P><b> Please fill out the evaluations.  You can find links to the evalutions on <A HREF="' + SEMINAR_FORM_URL + '"><b>HERE.</b></A>  Do this now!</b>.' 
    + "<P>"
    + "<P>" 
    + "<P>" 
    + "<P>--------------------------------------------------------"
    + "<P> <i>You are receiving this message because our records report that you have yet to complete a required seminar evaluations. </i>"
    + "<P> If you think this remind was sent in error, please <a href='mailto:robert_boland_1@brown.edu'><b>contact me</b></a> to prevent further nagging!"    
    + "<P>"     
    + "<P>_______________________________________________________________________________"
    + "</HTML></BODY>";
      if(row.name){  
      MailApp.sendEmail(row.name, "Reminder: Please complete your seminar evals!", "", {cc:DISTRIBUTE,htmlBody: message});
      } SpreadsheetApp.flush(); 
    } 
  }   

  } catch (e) {    
    MailApp.sendEmail("robert_boland_1@brown.edu", "Error report", e.message); 
  }
}

/////////////////////////////////////////////////////////////////////////////////
// Code reused from 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
//       This argument is optional and it defaults to all the cells except those in the first row
//       or all the cells below columnHeadersRowIndex (if defined).
//   - 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) {
  var headersIndex = columnHeadersRowIndex || range ? range.getRowIndex() - 1 : 1;
  var dataRange = range || 
    sheet.getRange(headersIndex + 1, 1, sheet.getMaxRows() - headersIndex, sheet.getMaxColumns());
  var numColumns = dataRange.getEndColumn() - dataRange.getColumn() + 1;
  var headersRange = sheet.getRange(headersIndex, dataRange.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(dataRange.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. 
// Empty Strings are returned for all Strings that could not be successfully normalized.
// Arguments:
//   - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    keys.push(normalizeHeader(headers[i]));
  }
  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';
}
4

1 に答える 1

1

行番号などの詳細情報を取得できるように、エラーを次の関数に解析してください。

/**
 * Parse errors stacktrace into a readable format.
 * This function never throws an error, so you don't need to try-catch it.
 * If the error cannot be processed, it will just return it silently.
 * @return {string} The error toString plus its stacktrack broke into multiple lines
 * @param {Error} e The error to be processed
 */
function parseErr(e) {
  try {
    var ret;
    if( e !== undefined && e !== null && e.stack && e.toString ) {
      ret = e.toString()+' \nStacktrace: \n';
      var stack = e.stack.replace(/\n/g,'').match(/:\d+( \([^\)]+\))?/g);
      for( var i in stack )
        ret += stack[i].replace(/[\(\):]/g,'').split(/ /).reverse().join(':') + ' \n';
    } else if( typeof(e) === 'object' )
      ret = inspect(ret);
    else
      ret = ''+e;
    return ret;
  } catch(suppress) {
    return ''+e;
  }
}

/**
 * Inspect an object properties and returns a nicely formatted string
 * Good to be logged or sent via email.
 * @return {string} inspection of the object's iterable elements
 * @param {*} o object to be inspected
 * @param {number=} optMaxLevel optional max level that function should go deep in the object
 *     Important to avoid infinite loops on recursive objects. Defaults to 4
 */
function inspect(o,optMaxLevel) {
  if( optMaxLevel === undefined )
    optMaxLevel = 4; //default inspect level
  else if( optMaxLevel < 1 )
    return '\n> maximum level must be equal to or greater than 1 (one)';
  if( o === null || o === undefined )
    return '\n> '+o;
  else {
    var tof = function(v) {
      try { return typeof(v); } //I don't now why typeof is throwing errors on arrays
      catch(e) { return 'object'; } //so I'm just defaulting to object
    };
    var ret = function innerInspect(o,maxLevel,level) {
      var msg = '';
      if( level.length > maxLevel ) {
        for( var i in o )
          msg += i+',';
        msg = '\n'+level+msg.substring(0,msg.length-1); //remove last comma
      } else {
        for( var i in o ) {
          var t = tof(o[i]);
          msg += '\n'+level+i+' :: '+t;
          try {
            if( t == 'object' && o[i] )
              msg += innerInspect(o[i],maxLevel,'>'+level);
            else if( t != 'function' )
              msg += ' = "'+o[i]+'"';
          } catch(e) {
            msg += '\n>'+level+e.message;
          }
        }
        if( msg == '' )
          msg = ' = "'+o.toString()+'"';
      }
      return msg;
    }(o,optMaxLevel+1,'> ');
    return ret.substring(0,2) == ' =' ? '\n> '+tof(o)+ret : ret;
  }
}

メールを送信する代わりにe.message、解析済みのスタックを送信するか、現在の変数の値をいくつか追加します。たとえば、次のようにします。

var moreInfo = inspect({i:i, row:row}) + '\n' + parseErr(e);
MailApp.sendEmail("yourself@etc", "Error report", moreInfo);
于 2012-07-11T04:31:36.307 に答える