如何减少在forloop中使用setValues()和copyto()的Google App脚本的运行时间
我找到一些代码并对其进行修改,以进行复制格式复制和粘贴
我不知道为什么要使用它setValues()和CopyTo(),但是它可以工作。
我认为问题是forloop中的某个类。但是,在这种情况下,我不知道如何将setValues(),copyto()与forloop分开
它工作正常,但是在forloop中由setValues()花费很多时间如何将它与forloop分开以加快速度
function Duplicate_Format() {
const SS = SpreadsheetApp.getActiveSpreadsheet();
const Source_NotationRange = "B6:B47";
const Target_Sheet = SS.getSheets();
const Source_Data_sheet = SpreadsheetApp.getActive().getSheetByName('01.01');
const Source_Data_Range = Source_Data_sheet.getRange(Source_NotationRange);
var Location_First = 4;
var Location_Quantity = 366;
const Location_Last = Location_First + Location_Quantity -1;
for( let j = Location_First ; j <= Location_Last; j++){
var Target_Sheets = Target_Sheet[j];
var Target_Range = Target_Sheets.getRange(Source_NotationRange);
Target_Range.setValues(Source_Data_Range.getValues());
Source_Data_Range.copyTo(Target_Range, {formatOnly:true});
}
}
我相信您的目标如下。
为了实现这一点,我建议使用Sheets API。在这种情况下,修改后的脚本的流程如下。
在运行脚本之前,请在Advanced Google services中启用Sheets API。
function Duplicate_Format() {
const SS = SpreadsheetApp.getActiveSpreadsheet();
const Source_NotationRange = "B6:B47";
const Target_Sheet = SS.getSheets();
const Source_Data_sheet = SpreadsheetApp.getActive().getSheetByName('01.01');
const Source_Data_Range = Source_Data_sheet.getRange(Source_NotationRange);
var Location_First = 4;
var Location_Quantity = 366;
const Location_Last = Location_First + Location_Quantity -1;
// I modified below script.
// 1. Create the request body for the CopyPasteRequest of the method of batchUpdate in Sheets API.
var requests = [];
var srcStartRow = Source_Data_Range.getRow() - 1;
var srcEndRow = srcStartRow + Source_Data_Range.getNumRows();
var srcStartCol = Source_Data_Range.getColumn() - 1;
var srcEndCol = srcStartCol + Source_Data_Range.getNumColumns();
for( let j = Location_First ; j <= Location_Last; j++){
var Target_Sheets = Target_Sheet[j];
var Target_Range = Target_Sheets.getRange(Source_NotationRange);
var dstStartRow = Target_Range.getRow() - 1;
var dstEndRow = dstStartRow + Target_Range.getNumRows();
var dstStartCol = Target_Range.getColumn() - 1;
var dstEndCol = dstStartCol + Target_Range.getNumColumns();
requests.push({
copyPaste:{
source:{sheetId:Source_Data_sheet.getSheetId(),startRowIndex:srcStartRow,endRowIndex:srcEndRow,startColumnIndex:srcStartCol,endColumnIndex:srcEndCol},
destination:{sheetId:Target_Sheets.getSheetId(),startRowIndex:dstStartRow,endRowIndex:dstEndRow,startColumnIndex:dstStartCol,endColumnIndex:dstEndCol},
pasteType:"PASTE_NORMAL"
}
});
}
// 2. Request to Sheets API using the created request body.
var res = Sheets.Spreadsheets.batchUpdate({requests: requests}, SS.getId());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句