如何限制公式可以运行的日期?

时间:2016-07-27 22:12:45

标签: google-apps-script

我正在创建一个谷歌工作表,每天跟踪谷歌文档中的字数。我已经找到了一种将字数统计到电子表格中的方法。现在我每天都这样设置:

E2=IF(A2=TODAY(), J2,)

这样可行,但一旦更新了字数,每个具有此公式的单元格都会更新。但是,我需要这个公式只在指定的日期运行,所以我可以看到当天的字数是多少,并且能够将其复制到下一行,仅在第二天运行,依此类推。我知道使用常规公式没有办法做到这一点,所以我需要一个脚本来使它工作。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可能会发现将一张专门用于存储每天发现的字数的表更容易。这里有一些代码可以帮助您满足需要。您所需要做的就是:

  1. 填写spreadsheetIdsheetNamedocumentId
  2. 设置installable trigger每天运行logMyWordCounts
  3. /**
     * This is the function to use for the installable trigger
     */
    function logMyWordCounts() {
      var spreadsheetId = "", // spreadsheet that contains log
          sheetName = "", // sheet to log to
          documentId = ""; // document to count words from
    
      var wordCount = getWordCount(documentId);
    
      logWordCount(spreadsheetId, sheetName, wordCount);
    }
    
    /**
     * Returns the word count of the document with the given id
     */
    function getWordCount(documentId) {
      var text= DocumentApp.openById(documentId).getBody().getText();
      text = text.split(/\s+/);
      return text[0] === "" ? 0 : text.length;
    }
    
    /**
     * Returns a string in the format of "m/d/year"
     */
    function formatDate(date) {
      return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getYear();
    }
    
    /**
     * Appends a row with the current date and given word count
     * to the sheet with the given name and spreadsheet id
     */
    function logWordCount(spreadsheetId, sheetName, wordCount) {
      var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
      var sheet = spreadsheet.getSheetByName(sheetName);
    
      sheet.appendRow([formatDate(new Date()), wordCount]);
    }