您可以使用srcSheet.getLastColumn()来获取最后一列内容。请注意,这将检索并索引(一个数字)而不是一个字母,但是在调用getRange时不需要使用A1 notation
,因此您可以使用该数字指示要获取的列。
不过,考虑到您想做什么,这对实现您的目标没有帮助。
实际上,您希望将A,D和E列专门复制到目标工作表的A,B,C列。
我对您的代码做了一些修改,以便它可以执行您想要的操作:
function copySheet() {
// Opens the spreadsheet where the data is stored
var sourceTable = SpreadsheetApp.openById("1sp8XFuOAGEfakS_td0xEiX3birz5ckoHNKvzrLPGTOI"); // Source file
var srcSheet = sourceTable.getSheetByName("Sheet1");
// Inserts the data into the target file
var targetTable = SpreadsheetApp.openById("1e6Dqyv14Edwj7JUFjZsM72IOj8Gh4-tMyUV4iGa-x6Q"); // Target file
var tarSheet = targetTable.getSheetByName("Sheet1");
// Gets the last row in the source file
var lastRowSource = srcSheet.getLastRow();
var originColumns = [1,4,5]; // Column indexes to be copied (A,D,E)
var destColumns = [1,2,3]; // Column indexes to copy to (A,B,C)
// Loop through each column to copy:
for(var i = 0; i < originColumns.length; i++) {
var originColumn = originColumns[i]; // Origin column index
var destColumn = destColumns[i]; // Destination column index
var originRange = srcSheet.getRange(1,originColumn,lastRowSource); // Origin range to copy
var destRange = tarSheet.getRange(1,destColumn,lastRowSource); // Destination range to be copied to
var values = originRange.getValues(); // Getting values from origin column
destRange.setValues(values); // Setting values to destination column
}
}
在此代码中,要复制的列索引在两个数组中定义(变量originColumns
和destColumns
),然后使用for
循环遍历每个原点和目标列(将数据从一个复制到另一个)。由于要复制的列(A,D,E)没有遵循特定的模式,因此无法以更系统的方式完成此操作。
我希望这对您有用。
,
建议的脚本对我有用,但是运行有点慢。由于源文件经常添加值,因此我在目标文件中有一个触发器设置,可以在打开时运行脚本。
我使用的脚本运行起来会更快一些:
function copySheet() {
// Opens the spreadsheet where the data is stored
var sourceTable = SpreadsheetApp.openById("1sp8XFuOAGEfakS_td0xEiX3birz5ckoHNKvzrLPGTOI"); // Source file
//Defines source sheet
var srcSheet = sourceTable.getSheetByName("Sheet1");
// Opens the destination spreadsheet
var targetTable = SpreadsheetApp.openById("1i77LO4W2paMraipyC_bgx09P7TAuL2cwEVCNxGnbjhs"); // Target file
//Defines destination target sheet
var tarSheet = targetTable.getSheetByName("Sheet1");
//Retrieves all values from source
var srcValues = srcSheet.getDataRange().getValues();
//For each row in source values,creates new array containing columns A(0),D(3) & E(4) inside of trimedValues array
var trimmedValues = srcValues.map(function(row) {
return[row[0],row[3],row[4]];
})
// Save trimmedValues array to destination
tarSheet.getRange(1,1,trimmedValues.length,3).setValues(trimmedValues);
}
本文链接:https://www.f2er.com/3118238.html