I have written a script on Google App Script that will, at one point, get a range from one sheet, copy the values on that range and paste them to another sheet.
I have done so by doing this:
var range = sh.getDataRange().offset(0, 0);
var data = range.getValues();
var ts = SpreadsheetApp.openById('SHEETID').getSheetByName('SHEETNAME')
ts.getRange(ts.getLastRow() + 1, 1, data.length, data[0].length).setValues(data)
I would like, however, to specify the exact range to copy and another exact range to paste the data into.
I would like the range to be copied/pasted to be from columns A to Z whilst still keeping the getLastRow() in the script.
How would I do that?
Thanks for your help.
You can use getRange(a1Notation) to fetch a range and its contents. I usually go for A1 notation. Sample:
// Get a range A1:D4 on sheet titled "Invoices"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange("Invoices!A1:D4");
// Get cell A1 on the first sheet
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("A1");
There are other variations of getRange you can use. Choose what you're comfortable with.
For copying and pasting altogether, you can use the copyTo(destination)
// The code below copies the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
Related
Here's my problem : i'm trying to copy a value from one cell in "sheet1" to another cell in "sheet2".
But I want to run this script everyday (using trigger) because the value change every day. So the paste has to be in B2 the first day, B3 the second day, etc. I want to be able to follow the value day by day and have an historic.
Here's my current script :
function backup(){
var sourceSheet = "Portfolio" ;
var sourceRange = "N15" ;
var targetSheet = "Suivi perfs journalières" ;
var targetRange = "B2:B999" ;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheet);
var values = sheet.getRange(sourceRange).getValues();
ss.getSheetByName(targetSheet).getRange(targetRange).setValues(values);
I have 2 problem :
My script send me this error : Exception: The number of rows of data does not match the number of rows in the range. There are 1 lines of data, but the range has 998. (line 12, "CopyPastePortfolioValue" file)
I don't know how to paste the value in a new cell everyday (paste in the cell under the previous each day)
Thanks for your help!
I believe your goal as follows.
You want to retrieve the value from the cell N15 in the source sheet and append the value to the target sheet.
Modification points:
When setValues(values) is used, the lengths of rows and columns of values are required to match to the range. In your script, values of var values = sheet.getRange(sourceRange).getValues(); is 1 row and 1 column. But the target range is B2:B999. By this, such error occurs. I think that this is the answer for your 1st question.
In order to append the value to the target sheet, in your case, I would like to propose to use appendRow. I think that this is the answer for your 2nd question.
And, when a value from a cell, you can also use getValue instead of getValues.
When above points are reflected to your script, it becomes as follows.
Modified script:
function backup(){
var sourceSheet = "Portfolio";
var sourceRange = "N15";
var targetSheet = "Suivi perfs journalières";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheet);
var value = sheet.getRange(sourceRange).getValue(); // Modified
ss.getSheetByName(targetSheet).appendRow([value]); // Modified
}
References:
setValues(values)
appendRow(rowContents)
I'm trying to build a script that will allow me to copy and value paste a range from tab "robert" to tab "brendan". However, the range in "robert" is dynamic, so sometimes it will need to copy and paste A1:M3 or A1:M20. I'd also like it to append to the the first rows of the destination. So when run, the script looks for values on the source tab (robert), copies them, and pastes their values at the top of the destination (brendan) without overwriting existing data.
So far I've worked with the below script from a different thread:
function moveValuesOnly() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source = ss.getRange('Robert!A1:M100');
source.copyTo(ss.getRange('Brendan!A4'), {contentsOnly: true});
source.clear();
}
The problem here is the script range is static, and it overwrites anything in the destination. I do like the clearing of the source though and the values paste. Any help would be greatly appreciated!
Define the range using variables. Use getLastRow() and getLastColumn() Instead of hard-coding it.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var robWs = ss.getSheetByName("Robert");
var brenWs = ss.getSheetByName("Brendan");
var robLr = robWs.getLastRow()
var robLc = robWs.getLastColumn()
//range starts at row 1 and column 1 (A1), you may need to change accordingly
var vals = robWs.getRange(1,1,lr,lc).getValues;
//paste range also starts at A1. you can find the lr on this sheet and start the range there
brenWs.getRange(1,1,lr,lc).setValues(vals);
function moveValuesOnly() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Robert');
var rg=sh.getActiveRange();//copies active range for source
var vA=rg.getValues();
dsh=ss.getSheetByName('Brendan');
dsr=4;//destination start row
dsc=1;//destination start col
dsa=2;//destination number of rows to append to
drg=dsh.getRange(dsr,dsc,rg.getHeight(),rg.getWidth());
var dvA=drg.getValues();
vA.forEach(function(r,i){
if(i<dsa){
r.forEach(function(c,j){
//only write data in destination for these rows if destination value is null
if(dvA[i][j]='') {
dvA[i][j]=c;
}
});
}else{
dvA[i][j]=c;
}
})
drg.setValues(dvA);
}
I'm trying to put together a script that cuts a range from a google spreadsheet and pastes it to another spreadsheet. The script works fine as long as the source sheet is the first sheet in my document. How can I fix it so that the script grabs the right sheet no matter where it is in my document?
I'm very very new at this and mostly used code I found online. Probably made a very obvious mistake..
function CopyRangeTo_OtherSheet() {
var sss = SpreadsheetApp.openById('1O1gML-IeOkx6n6RhCavay6Zg9zflalcVs0qkB2yu7bE');
var ss = sss.getSheetByName('Sheet1');
var range = ss.getRange(2,4,sss.getLastRow()-1,9);
var data = range.getValues();
var tss = SpreadsheetApp.openById('1WHoETM3QxV166ndnPW4Qv37Y6SBGPVw-CcEQxNpw0Co');
var ts = tss.getSheetByName('Sheet3');
ts.getRange(ts.getLastRow()+1, 1,50,9).setValues(data);
var spread = SpreadsheetApp.openById('1O1gML-IeOkx6n6RhCavay6Zg9zflalcVs0qkB2yu7bE');
var sheet = spread.getSheetByName("Sheet1");
sheet.getRange("D2:H").clearContent();
}
The number of rows will be different in each sheet. .getLastRow() on a spreadsheet class only returns the last row in first sheet. getLastRow of sheet instead
ss.getLastRow()
Your line var ss = sss.getSheetByName('Sheet1'); implies that you take the sheet with the name Sheet1.
This is the sheet you use to obtain your values from range and subsequently copy them.
If you want to copy / cut and paste values from a different sheet, simply paste the correct name of the sheet in var ss = sss.getSheetByName('PASTE HERE THE NAME OF THE SHEET');
Small annotation:
If the range you want to clear is the same from which you copied the
values, you do not need to define it again. You can simply replace the
lines
var spread = SpreadsheetApp.openById('1O1gML-IeOkx6n6RhCavay6Zg9zflalcVs0qkB2yu7bE');
var sheet = spread.getSheetByName("Sheet1");
sheet.getRange("D2:H").clearContent();
through
range.clearContents();
Also note:
setValues() only works if the range into which the values shall be set has the same dimension like the value range, i.e. the original range.
If your original range is 2,4,ss.getLastRow()-1,9, then the number of rows is ss.getLastRow()-1 and the number of columns 9.
Thus, you need to define
ts.getRange(ts.getLastRow()+1, 1,ss.getLastRow()-1,9).setValues(data);
to adapt the row number dynamically.
I'm trying to make a copy of one spreadsheet using a (time driven) Google App Script. I found a very useful piece of code here, but my concern is that the range varies frequently (new rows are added). How can I copy the entire spreadsheet no matter if the range changes?. because as you can see in the code below I have defined the range, but when this changes the information out of the defined range will be discarded. What can I do?
Thanks in advance.
Here the code I'm using:
function saveAsSpreadsheet(){
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange('sheetName!A1:AO158');
sheet.setNamedRange('sheetName', range);
var TestRange = sheet.getRangeByName('sheetName').getValues();
Logger.log(TestRange);
var destFolder = DriveApp.getFolderById("folderID");
DriveApp.getFileById(sheet.getId()).makeCopy("FileName:"+ timestamp, destFolder);
}
If you need to get the range object defined by the first cell of column A and the last cell in column A that contains data, use this code:
var range = sheet.getRange(1, 1, sheet.getLastRow(), 1);
The getRange() method has several overloads and can accept numerical values defining the boundaries of the range as well. More on this here https://developers.google.com/apps-script/reference/spreadsheet/sheet#getRange(Integer,Integer)
If you need to copy everything, use getDataRange() method.
I am able to copy a range of values from one spreadsheet to another with Range.setValues(values) but not with Range.copyValuesToRange(sheet, column, columnEnd, row, rowEnd):
function test()
{
var sourceSheet = SpreadsheetApp.getActiveSheet();
var sourceCols = sourceSheet.getRange("A1:B10");
// Copying the first two columns this way works.
var sheet1 = SpreadsheetApp.create("New Spreadsheet 1").getActiveSheet();
sheet1.getRange("A1:B10").setValues(sourceCols.getValues());
// Copying the first two columns this way does not work.
var sheet2 = SpreadsheetApp.create("New Spreadsheet 2").getActiveSheet();
sourceCols.copyValuesToRange(sheet2, 1, 2, 1, 10);
}
Specifically, after running the code, New Spreadsheet 1 contains range A1:B10 of the source spreadsheet, while New Spreadsheet 2 is empty. Both have a single sheet named "Sheet1". The source spreadsheet is unmodified.
What am I doing wrong? I'm wondering if the failing method only works within a single spreadsheet, but I see nothing in the documentation about that.
The reason I want to use Range.copyValuesToRange() is so I can also copy the formatting with Range.copyFormatToRange().
The methods copyValuesToRange and copyFormatToRange, as well as Range.copyTo, are restricted to copying within the same spreadsheets, although documentation is not explicit about that. A workaround which allows you to copy between spreadsheets with formatting is to copy the entire sheet to the destination spreadsheet, using Sheet.copyTo method. Then copy the required range from there, and optionally, delete the sheet. Like this:
function cc() {
var ss1 = SpreadsheetApp.openByUrl('some url');
var ss2 = SpreadsheetApp.openByUrl('another url');
var sheet1 = ss1.getSheetByName('name');
var sheet2 = ss2.getSheetByName('another name');
// the above was the setup, main code begins here
var copySheet = sheet1.copyTo(ss2);
copySheet.getRange("A1:B2").copyTo(sh2.getRange("C1:D2"));
ss2.deleteSheet(copySheet);
}