2016-09-07 62 views
0

在Google SpreadSheet中,工作表1有3个值。 [持续时间由= DATEDIF(开始日期,结束日期, “M”)计算的]基于另一个工作表值的一张工作表中的动态列 - Google表格

enter image description here

Sheet 2中有2个预定义的列(Col1中,Col2中),并且需要基于所述持续时间的值要追加动态列。

Example 1: 
StartDate = 01-Sep-2016 and EndDate = 30-Nov-2016 
So the Duration is 2 

enter image description here

Example 2: 
StartDate = 01-Sep-2016 and EndDate = 31-Dec-2016 
So the Duration is 3 

enter image description here

作为列是动态的,是有可能设置基于列和行索引的列值,而不是硬编码为以下代码。

function onOpen() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var s1= ss.getSheetByName("Sheet1"); 
    var s2= ss.getSheetByName("Sheet2"); 
    var sDate = s1.getRange("B5").getValue(); 
    var sDuration = s1.getRange("B7").getValue(); 
    var sMonth = Utilities.formatDate(sDate, Session.getScriptTimeZone(), "MMM"); 
    var sYear = Utilities.formatDate(sDate, Session.getScriptTimeZone(), "YYYY"); 
    for (var cell = 1; cell <= sDuration; cell++) { 
     s2.getRange("C1").setValue(sMonth + ", " + sYear); 
    } 
} 

谢谢。

回答

0

您找到解决方案的80%,我只是增加了一些修正你的代码,使其工作动态:

function myFunction(){ 

    onOpen(); 
} 

function onOpen() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var s1= ss.getSheetByName("Sheet1"); 
    var s2= ss.getSheetByName("Sheet2"); 
    var sDate = new Date(s1.getRange("B1").getValue()); // changed to B1 - the start date value, and sDate must be a Date Object, not string. 
    var sDuration = s1.getRange("B3").getValue(); // changed to B3 - the duration value 
    for (var cell = 0; cell < sDuration; cell++) { // cell starts from 0 
    var sMonth = Utilities.formatDate(sDate, Session.getScriptTimeZone(), "MMM"); // I moved this into FOR loop 
    var sYear = Utilities.formatDate(sDate, Session.getScriptTimeZone(), "YYYY"); // I moved this into FOR loop 
    s2.getRange(1,cell+3).setValue(sMonth + ", " + sYear); // geting range with row & column value, not with Column name 
    sDate.setMonth(sDate.getMonth()+1); // add one month to sDate 
    } 
} 

有在哪里我改变了代码的注释。我希望你觉得这有帮助。

0

略微修改了Change value of cell in same row with google script if column has certain value中的代码,它的工作原理。

改性的OnOpen()是,

function onOpen() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var s1= ss.getSheetByName("Sheet1"); 
    var s2= ss.getSheetByName("Sheet2"); 
    var sDate = s1.getRange("B5").getValue(); 
    var sDuration = s1.getRange("B7").getValue(); 
    var lastColumn = s2.getLastColumn(); 
    for (var cell = 3; cell <= lastColumn + sDuration; cell++){ 
    var currentCell = s2.getRange(1, cell); 
    currentCell.setValue(Utilities.formatDate(sDate, Session.getScriptTimeZone(), "MMM") + ", " 
        + Utilities.formatDate(sDate, Session.getScriptTimeZone(), "YYYY")); 
    sDate.setMonth((sDate.getMonth() + 1) % 12); 
    } 
} 
相关问题