Google Sheets Auto Copy, Paste, Delete - google-apps-script

Does anyone know a script that would let me copy data from cells A3:E1000 on Sheet1 and paste it to Sheet2. After pasting I need it to delete the exact data that it copied from Sheet1 (Sheet2 will still have copied data) and I need it to do this everyday at 11:30pm. I need Sheet2 to be able to keep taking the data forever as a digital archive of the data that is being copied daily from Sheet1. I hope this makes sense. I can't figure it out. When I run this it works if I run dailyLog and then run clearRange separately. When I run autoArchive it deletes the data from Info sheet but doesn't paste it into the Archive sheet.
function autoArchive(){
dailyLog();
clearRange();
}
function dailyLog() {
var ss = SpreadsheetApp.openById("SheetID").getSheetByName("Info");
var sourceSheet = ss.getSheetByName('Info');
var logSheet = ss.getSheetByName('Archive');
var lastRow = logSheet.getLastRow();
var range = sourceSheet.getDataRange();
range.copyTo(logSheet.getRange(lastRow + 2, 1), {contentsOnly: false});
}
function clearRange() {
var sheetActive =
SpreadsheetApp.openById("SheetID").getSheetByName("Info");
var start, end;
start = 2;
end = sheetActive.getLastRow() - 1;
sheetActive.deleteRows(start, end);
}

have a look at the record macro function it will generate Google Apps Script for you. Just records the steps you take and give it a name so you only need to click the macro in the menu or use a shortcut.
#Cooper the current limit for a spreadsheet is 5.000.000 cells. Doesn't matter if it is in one sheet or all sheets together. However this might be increased in the nearby future.

Use SpreadsheetApp.flush(); to force Google Apps Script to apply the changes made so far.
Example:
function autoArchive(){
dailyLog();
SpreadsheetApp.flush();
clearRange();
}

Related

How to save on the next row from one existing data of copied google spreadsheet to another google spreadsheet using google apps script?

I have this dilemma where i recorded a macro to copy a row to another sheet but so happens every time i run the macro it will always save on the same row. what can I add to this script in order for the macro to save it after the previously saved data?
Current Code:
function SAVING2() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A2:O2').activate();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Audit RAW'), true);
spreadsheet.getRange('A2').activate();
spreadsheet.getRange('\'audit dump\'!A2:O2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
What I wish to accomplish:
For the macro to save the next set of data after the previous
Your help would be greatly appreciated
In your script, from spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Audit RAW'), true); and spreadsheet.getRange('A2').activate();, the destination range is always "A2" of "Audit RAW" sheet. I think that this is the reason of your issue. In your situation, how about the following modification?
Modified script:
function SAVING2() {
var spreadsheet = SpreadsheetApp.getActive();
var src = spreadsheet.getRange('\'audit dump\'!A2:O2');
var dstSheet = spreadsheet.getSheetByName("Audit RAW");
var dst = dstSheet.getRange(dstSheet.getLastRow() + 1, 1);
src.copyTo(dst, SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
}
In this modification, the destination range is set as the next row of the last row. By this, the copied value is appended to the destination sheet.
Reference:
getLastRow()

Is possible to copy a data range from one spreadsheet to another?

function transferDataToDataBase(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var DB = SpreadsheetApp.openById("SHEET ID");
var SCPM_Input = ss.getSheetByName("Report")[0];
var history_Input = DB.getSheetByName(Database);
var blankRow = history_Input.getLastRow();
SCPM_Input.getRange(("A2:T").copyTo(history_Input.getRange(blankRow+1,1,blankRow+1,20));
}
Question:
The last line has an error at ";", don't know how to fix it. It said the syntax error;
It seems copy To only works for transferring from one sheet to another in the same spreadsheet, but not in between spread sheet. Is there a way to copyTo between spreadsheets?
Many thanks.
If you want to copy the formatting as well then copy the entire sheet/tab and then use copyTo() to copy the range and then delete the copied sheet. Or if you just want the data use getValues() and setValues();
This is part of the problem:
var SCPM_Input = ss.getSheetByName("Report")[0]; because the index zero at the end should not be there and you cannot have sheet.getLastRow() + 1 number of rows in a sheet as shown in the next row.
SCPM_Input.getRange(("A2:T").copyTo(history_Input.getRange(blankRow+1,1,blankRow+1,20));
And copyTo doesn't work between spreadsheets.
There is an update:
Since the database will be used by multiple users. I set up a standalone database. I copied my "Report" sheet from spreadsheet 1 to spreadsheet 2. It will create a sheet "copy of Report".I rename, copied to Database sheet and delete it.
Feel free to discuss if there is an easier way to do it. Thanks.
// transfer the report to DataBase Spreadsheet
function transferDataToDataBase(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var db = SpreadsheetApp.openById('spreadsheet ID')
var scpm_Input = ss.getSheetByName("Report");
scpm_Input.copyTo(db);
Utilities.sleep(3000);
db.getSheetByName('copy of report').setName('Import')
var history_Input = db.getSheetByName('Database');
var blankRow = history_Input.getLastRow();
var target = db.getSheetByName('Import');
target.getRange("A2:T").copyTo(history_Input.getRange(blankRow+1,1,blankRow+1,20));
history_Input.getRange(blankRow+1,21).setValue(new Date()).setNumberFormat("yyyy-mm-dd h:mm") //update the date and time
db.deleteSheet(target);
}

Why can't I copy ranges between spreadsheets with copyValuesToRange()?

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);
}

Google Script: Issue deleting Specific Sheet in google spreadsheet

Situation:
I have a spreadsheet with 20 sheet.
I have other script that copy sheets from other spreadsheet every days to this spreadsheet-
I need to delete every days some specific sheet from a particular spreadsheet.
Problem:
When the script ends to clear the sheets, the spreadsheet hangs and I have to exit and re-enter to the spreadsheet.
I'll appreciate if anyone can help to tunning this script to work without hangging the spreadsheet.
Script:
function shellDeleteSheets(){
var sheets = ['Sheet1','Sheet2','Sheet3','Sheet4','Sheet5'];
for (var s in sheets){
deleteSheetName(sheets[s]);
}
}
function deleteSheetName(stname) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName(stname);
if(!sh) {
return;
}
ss.setActiveSheet(sh);
ss.deleteActiveSheet();
Utilities.sleep(400);
SpreadsheetApp.flush();
}
Try this version I use without issue
function DeleteSheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ['sheet1','sheet2','sheet3'];
var numberOfSheets = ss.getSheets().length;
for(var s = numberOfSheets-1; s>0 ; s--){ // in my case I never delete the first sheet
SpreadsheetApp.setActiveSheet(ss.getSheets()[s]);
var shName = SpreadsheetApp.getActiveSheet().getName();
if(sheets.indexOf(shName)>-1){
var delSheet = ss.deleteActiveSheet();
Utilities.sleep(500);
}
}
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);// send me back to first sheet
}
You could of course use the array of names as an argument for the function or - that's what I do in some cases - give the names of the sheet I need to keep, in this case the if condition is just different .
the sleep can be 400 mS, not sure it makes any difference, I use 500 because at some time I found it more reliable... and I (try to) never change a working solution ;-)
EDIT following your comment :
to make active the sheet called 'Updated' just change the last line of the code like this :
SpreadsheetApp.setActiveSheet(ss.getSheetByName('Updated'));
please note also that I moved this line in the original code, outside of the loop, sorry for this small error ^^

copyTo using {contentsOnly:true} not working

As a caveat, I am very new to Google Apps scripting. I appreciate any assistance that can be provided.
I am trying to copy the contents of a sheet into a new document. This code works without any problem:
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet);
However, this copies over the formulas from the current sheet - I am trying to copy the values only, as the formulas reference data on other sheets in the original document.
My attempt to do this is as follows:
// Create a new Spreadsheet and copy the current sheet into it.
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var projectname = SpreadsheetApp.getActiveSpreadsheet();
sheet = originalSpreadsheet.getActiveSheet();
sheet.copyTo(newSpreadsheet, {contentsOnly:true})
However, this generates the following error: Cannot find method (class)copyTo($Proxy914,object).
I am unsure what I am doing wrong. Any assistance would be appreciated. Thanks in advance!
There are actually 2 copyTo, one applies to sheet and the other applies to Range
According to the documentation (see links above), the second one has optional argument to copy values only while the first has not.
What I guess you could do is use the Range.copyTo() to copy the whole sheet range to a temporary sheet (in the same spreadsheet) and then copy that temporary sheet to the other spreadsheet and finally delete the temporary sheet from the source spreadsheet.
Hoping it is clear enough ;-)
In the script gallery there is a script called spreadsheetFrozenBackup, through which a copy of a spreadsheet can be made.
The range.copyTo that Serge alludes to is used.
It is not a long script, so I reproduce it here for information:
// Make copy of current spreadsheet with backup name.
function spreadsheetFrozenBackup() {
// Get current spreadsheet.
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Name the backup spreadsheet with date.
var bssName = ss.getName() + " frozen at " + Utilities.formatDate(new Date(), "GMT", "yyyyMMdd HHmmss");
var bs = SpreadsheetApp.openById((DocsList.copy(DocsList.getFileById(ss.getId()), bssName)).getId());
// Make sure all the formulae have been evaluated...
SpreadsheetApp.flush();
// Get all the sheets in the spreadsheet
var bsl = bs.getSheets();
var pl = "";
for (var i = 0; i < bsl.length; i++) {
bsl[i].getDataRange().copyTo(bsl[i].getDataRange(), {contentsOnly:true});
pl = pl + " " + bsl[i].getName();
SpreadsheetApp.getActiveSpreadsheet().toast(pl, "Processed Sheets");
}
SpreadsheetApp.getActiveSpreadsheet().toast(bssName, "Frozen Backup");
}