【问题标题】:Copy data from one sheet, add current date to each new row, and paste从一张表复制数据,将当前日期添加到每个新行,然后粘贴
【发布时间】:2018-04-09 10:31:12
【问题描述】:

我已经阅读了一些内容,但我对脚本的了解有限,这让事情变得很困难。我想:

  1. 从一张标题为“下载”的工作表中复制可变数量的行数据范围(已知列)
  2. 将该数据粘贴到 B 列标题为“交易历史”的新工作表中
  3. 在新工作表中,为复制的每条记录在新列 A 中添加格式为 (DD/MM/YYYY) 的今天日期

The data in worksheet 'Download' uses IMPORTHTML

The data copied from Download to store a historical record needs a date in Column A

我已经设法让 1 和 2 工作,但无法解决第 3 个问题。请参阅下面的当前脚本。

function recordHistory() {
var ss = SpreadsheetApp.getActive(),
sheet = ss.getSheetByName('Trade_History');
var source = sheet.getRange("a2:E2000");
  ss.getSheetByName('Download').getRange('A2:E5000').copyTo(sheet.getRange(sheet.getLastRow()+1, 2))
  }

【问题讨论】:

    标签: date google-apps-script google-sheets


    【解决方案1】:

    您需要使用Utilities.formatDate() 将今天的日期格式化为 DD/MM/YYYY。

    因为您要复制一组值,然后在它旁边(在 A 列中)粘贴另一个值,所以我也稍微修改了您的代码。

    function recordHistory() {
      var ss = SpreadsheetApp.getActive(),
          destinationSheet = ss.getSheetByName('Trade_History');
      var sourceData = ss.getSheetByName('Download').getDataRange().getValues();
      for (var i=0; i<sourceData.length; i++) {
        var row = sourceData[i];
        var today = Utilities.formatDate(new Date(), 'GMT+10', 'dd/MM/yyyy'); // AEST is GMT+10
        row.unshift(today); // Places data at the beginning of the row array
      }
      destinationSheet.getRange(destinationSheet.getLastRow()+1, // Append to existing data
                                1, // Start at Column A
                                sourceData.length, // Number of new rows to be added (determined from source data)
                                sourceData[0].length // Number of new columns to be added (determined from source data)
                               ).setValues(sourceData); // Printe the values
    }
    

    从源数据的getting the values 开始。这将返回一个数组,可以循环添加今天的日期。将日期添加到所有源数据后,确定打印位置的范围边界。现在必须定义完整尺寸,而不是像使用copyTo() 方法那样简单地选择起始单元格。最后,将值打印到定义的范围内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 2011-07-21
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多