[英]Google Sheets Apps Script Copy Row of Data If date same as tab name
I found some code that almost does what i need and have tried playing around with it to get it to work, but no luck.我发现了一些几乎可以满足我需要的代码,并尝试使用它来让它工作,但没有运气。 I get an export with data with dates in the last column on every row.
我得到一个导出数据,每一行的最后一列都有日期。
I simply want to copy the last column rows of dates to the tabs with the same name.我只想将日期的最后一列行复制到具有相同名称的选项卡中。
function MoveDate_FourthDEC() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName("Import");
var sh2=ss.getSheetByName("4/12/2020");
var rg1=sh1.getRange(2,1,sh1.getLastRow(),32);//starting at column2
var data=rg1.getValues();
for(var i=0;i<data.length;i++) {
// 13 = collected should be in this column which is column N
if(data[i][31]=="4/12/2020") {
sh2.appendRow(data[i]);
}}}
Your goal is to copy all the rows for which column AF
matches the names of the sheets.您的目标是复制
AF
列与工作表名称匹配的所有行。
To begin with, you can use forEach() to iterate over every sheet.首先,您可以使用forEach()迭代每个工作表。 For each sheet, you want to check whether the sheet name matches a date in column
AF
.对于每个工作表,您要检查工作表名称是否与
AF
列中的日期匹配。 If it does, then you need to filter only the rows that contain this date in column AF
and store them into an temporary array:如果是,那么您只需要过滤列
AF
中包含此日期的行并将它们存储到一个临时数组中:
let temp_data = data.filter(r=>r[31]==sh.getName());
Then you can efficiently copy and paste all the relevant rows to the matching sheet:然后,您可以有效地将所有相关行复制并粘贴到匹配的工作表中:
sh.getRange(sh.getLastRow()+1,1,temp_data.length,temp_data[0].length).setValues(temp_data);
Side notes:旁注:
When dealing with date objects you need to consider the display values in the sheet.在处理日期对象时,您需要考虑工作表中的显示值。 This is why I am using getDisplayValues instead of getValues .
这就是我使用getDisplayValues而不是getValues 的原因。
Since data
starts from the second row, you need to deduct one row from the last row with content, to get the correct range:由于
data
从第二行开始,您需要从最后一行内容中减去一行,以获得正确的范围:
getRange(2,1,sh1.getLastRow()-1,32)
I am using includes to check if the sheet name matches the last column.我正在使用包含来检查工作表名称是否与最后一列匹配。 In order to use
includes
you need to flat ten the 2D array that is returned by the getDisplayValues
function.为了使用
includes
您需要将getDisplayValues
函数返回的二维数组平铺10。
function MoveDate_FourthDEC() {
const ss = SpreadsheetApp.getActive();
const sh1 = ss.getSheetByName("Import");
const shs = ss.getSheets();
const dts = sh1.getRange('AF2:AF'+sh1.getLastRow()).getDisplayValues().flat();
const data=sh1.getRange(2,1,sh1.getLastRow()-1,32).getDisplayValues();
shs.forEach(sh=>{
if (dts.includes(sh.getName())){
let temp_data = data.filter(r=>r[31]==sh.getName());
sh.getRange(sh.getLastRow()+1,1,temp_data.length,temp_data[0].length).setValues(temp_data);
}});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.