在Google SpreadSheet中,Sheet1有3个值。 [持续时间由= DATEDIF(StartDate,EndDate," M")计算]
Sheet2有2个预定义列(Col1,Col2)和需要根据持续时间值追加的动态列。
Example 1:
StartDate = 01-Sep-2016 and EndDate = 30-Nov-2016
So the Duration is 2
Example 2:
StartDate = 01-Sep-2016 and EndDate = 31-Dec-2016
So the Duration is 3
由于列是动态的,是否可以根据列和行索引设置Columns值,而不是像下面的代码那样硬编码。
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 :(得分: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
}
}
我对更改的代码有评论。我希望你觉得这很有帮助。
答案 1 :(得分: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);
}
}