1

尝试编码一个函数,当选择某个菜单项时,将在电子表格的打开工作表底部调用并复制某些数据 - 当前数据正在从“示例的工作表逐行排列,所以我试图将rowNumber传递给duplicateLastRow函数 - 目前,它返回一个空值,我找不到原因。Google sheet返回null值为getRange

我也很喜欢这样做的不同方式,因为我的菜单有80个项目,因此有80个函数定义,我觉得500行代码是过度复制和粘贴命令的东西。代码包括在下面,并链接到此处公开:https://docs.google.com/spreadsheets/d/1yOJ8VdhbkbC9vw5or4geV-mv-PCk-WA86L8-F7-WGM8/edit?usp=sharing 在脚本编辑器中的项目称为copyRowFromOriginToDestination,我正在处理的脚本称为testFileBlarg - Code2脚本是我正在尝试的代码的工作但巨大版本从中删除对话框提示和行。

提前干杯!

function onOpen() { 
    var ui = SpreadsheetApp.getUi(); 

    ui.createMenu('testRow') 
    .addSubMenu(ui.createMenu('Life Sciences') 
    .addSubMenu(ui.createMenu('NRG') 
    .addItem('Highlight/Alamy', 'callHANRG') 
    )) 
    .addToUi(); 

} 

function callHANRG(rowNumber){ 
    duplicateLastRow(3); 
} 

function duplicateLastRow(rowNumber){ 

    var originSheetName = "Example Rows"; 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); // This is an object that represents the open spreadsheet 
    var originSheet = ss.getSheetByName(originSheetName); // This object represents the sheet we are copying FROM 
    var destinationSheet = ss.getActiveSheet() // getSheetByName(destinationSheetName); // This object represents the sheet we are copying TO 

    destinationSheet.insertRowAfter(destinationSheet.getLastRow()); // This adds a row to the end of the destination sheet so it doesn't fill up! 

    var originRow = originSheet.getRange(rowNumber, 1, 1, originSheet.getLastColumn()); // This object represents the row to be copied 
    var destinationRow = destinationSheet.getRange(destinationSheet.getLastRow()+1, 1); // This object represents the row we are copying to 

    originRow.copyTo(destinationRow); // This actions the copying 
} 
+0

从我的理解从你的代码是你想写一个函数将数据从一个工作表复制到其他的,正确的? –

+0

是的,这是我想要的,除非有一个更好的方法来生成工作表中的数据 - 我一直在看数组,但我真的对这一切知之甚少 –

+0

检查我的答案,它应该那么 –

回答

0

如果您想将数据从一张工作表复制到其他人,请参阅下面的代码以开始使用。

更新:

要使用此功能作为一个普通的功能来复制数据,例如 -

function callHANRG(rowNumber){ 
    copy(3, "A2:I20"); 
} 

然后在Copy()功能,

function Copy(rowNumber, rangeToBeCopied) 
{ 
    var sss = SpreadsheetApp.openById('<SPREADSHEET_ID>'); 
    var ss = sss.getSheetByName('Front'); 
    var range = ss.getRange(rangeToBeCopied); 
    var data = range.getValues(); 

    //If your copying data to different spreadsheet then only use this line or 
    //else use var ts = sss.getSheetByName('frontBackup'); and comment the two lines below. 
    var tss = SpreadsheetApp.openById('<SPREADSHEET_ID>'); 
    var ts = tss.getSheetByName('frontBackup'); 
    ts.getRange(rowNumber, 1, data.length, data[0].length).setValues(data); 
} 
+0

是的,这看起来与我的想法非常相似?我的问题是,我希望X中的ts.getRange(X,1,data.length,data [0] .length).setValues(data);根据所选的菜单项而变化。目前我正在使用变量rowNumber,它似乎没有传递。 –

+0

@KateSnowdon检查我的答案 –