Renaming a file in google sheet to previous month name using script - google-apps-script

I want to create a backup sheet of a google sheet file and its name should be "previous month name + year". Backup file is created, renaming the file is not happening.
function Copy() {
var sss =
SpreadsheetApp.openById('1IK6YsZS3_NNAlFA41d8uKriPzfZs_2Ukyh94eeBFj40');
var ss = sss.getSheetByName('CURRENT');
var range = ss.getRange('A1:H45');
var data = range.getValues();
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName("prevMonth");
if (yourNewSheet != null)
{
activeSpreadsheet.deleteSheet(yourNewSheet);
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName("prevMonth");
yourNewSheet.getRange(yourNewSheet.getLastRow()+1,1,45,8).setValues(data);
}

By using the code below:
function Copy() {
var sss = SpreadsheetApp.openById('1IK6YsZS3_NNAlFA41d8uKriPzfZs_2Ukyh94eeBFj40');
var ss = sss.getSheetByName('CURRENT');
var range = ss.getRange('A1:H45');
var data = range.getValues();
var d = new Date();
d.setMonth(d.getMonth() - 1);
var prevMonth = Utilities.formatDate(d, 'GMT+1', 'MMMM yyyy');
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName(prevMonth);
if (yourNewSheet != null) {
activeSpreadsheet.deleteSheet(yourNewSheet);
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName(prevMonth);
yourNewSheet.getRange(yourNewSheet.getLastRow()+1,1,45,8).setValues(data);
}
It will create a Sheet named "October 2019".

Related

Copy Specific Sheet from Drive Folder and Paste Data into Active Sheet

I have 10 to 15 Files in the Drive Folder All files have more than 1 Google sheets in it with some sort of Conditional Formatting.
I want to copy the Specific Sheet Named "MasterSheet" from each File and Combine the data into the Active Sheet where from script is bieng run.
Copied data should keep conditional formatting cell color. I will appreciate the help. Thanks
function myFunction()
{
var myFolder = DriveApp.getFolderById("FolderID");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var ActiveSpreadSheet = SpreadsheetApp.getActive().getSheetByName(Sheet1);
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
for(var y in spreadSheet.getSheets())
{
spreadSheet.getSheets()[y].copyTo(ActiveSpreadSheet);
}
}
}
UPDATE to check if there's a sheet called that way:
function copywithLog()
{
var destinsheet = SpreadsheetApp.getActiveSpreadsheet()
var myFolder = DriveApp.getFolderById("16CxTO70ipcUt8U_beokid3vFOOLGTnPh");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var activeSpreadSheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var i = 1
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
var sheets = spreadSheet.getSheets()
var filtered = sheets.filter(n => ["DATA"].lastIndexOf(n.getSheetName()) == 0)
if (filtered.length==1){
var newsheet = spreadSheet.getSheetByName('DATA').copyTo(destinsheet)
newsheet.getDataRange().copyTo(activeSpreadSheet.getRange(activeSpreadSheet.getLastRow()+2,1))
destinsheet.deleteSheet(newsheet)
Logger.log("Process successfully finished with the workbook named '"+spreadSheet.getName()+"'")}
else Logger.log("The worbook named '"+spreadSheet.getName()+ "' does not have a sheet called DATA")
}
}
It returns something like this:
UPDATE:
function copyinsamesheet()
{
var destinsheet = SpreadsheetApp.getActiveSpreadsheet()
var myFolder = DriveApp.getFolderById("FolderID");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var activeSpreadSheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var i = 1
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
var newsheet = spreadSheet.getSheetByName('MasterSheet').copyTo(destinsheet)
newsheet.getDataRange().copyTo(activeSpreadSheet.getRange(activeSpreadSheet.getLastRow()+2,1))
destinsheet.deleteSheet(newsheet)
}
}
If it has always the same name, you can try with this:
function copyMasterSheets()
{
var destinsheet = SpreadsheetApp.getActiveSpreadsheet()
var myFolder = DriveApp.getFolderById("FolderID");
var spreadSheets = myFolder.getFilesByType("application/vnd.google-apps.spreadsheet");
var ActiveSpreadSheet = SpreadsheetApp.getActive().getSheetByName(Sheet1);
var i = 1
while(spreadSheets.hasNext())
{
var sheet = spreadSheets.next();
var spreadSheet = SpreadsheetApp.openById(sheet.getId());
spreadSheet.getSheetByName('MasterSheet').copyTo(destinsheet).setName('MasterSheet '+i)
i++
}
}
An addendum to the answer by #Martin.
This takes the data on the various "Master Sheets" and copies it to a single sheet.
The range of data on each sheet is established dynamically, and is stacked down the page.
function copyMasters(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var target = ss.getSheetByName('Sheet1')
// idetify the starting row
var activeStartRow = 1
// get an array of all the sheets with names like "MasterSheet"
var sheetList = new Array
var sheets = ss.getSheets()
//var sourcesheet = ss.getSheets().find(sheet => sheet.getName().includes("MasterSheet"))
var mastersheets = sheets.filter(sheet => sheet.getName().includes("MasterSheet"))
//loop through the Master sheets
for (var i=0;i<mastersheets.length;i++){
var mastername = mastersheets[i].getName()
var master = ss.getSheetByName(mastername)
var masterLC = master.getLastColumn()
var masterLR = master.getLastRow()
// calculate the start row for the target sheet
if (activeStartRow==1){
var startRow =1
}else{
var startRow=startRow+masterLR
}
activeStartRow = 0
var rangeToCopy = master.getRange(1, 1, masterLR,masterLC)
//Logger.log("DEBUG: range to copy:"+rangeToCopy.getA1Notation())
var targetRange = target.getRange(startRow, 1, masterLR,masterLC)
//Logger.log("DEBUG: target range:"+targetRange.getA1Notation())
rangeToCopy.copyTo(targetRange)
// Logger.log("DEBUG: copied the data for "+mastername)
}
}
SAMPLE

Using Google Script I want to add a timestamp to each row of the result

I want to add a timestamp to each row of the result. I have attempted to add a separate timestamp script on edit but that is not working. Below is the code I am using.
function importCSVFromGmail() {
var threads = GmailApp.search("Gmail Search");
var message = threads[0].getMessages();
var attachment = message[message.length - 1].getAttachments()[1];
var sheet = SpreadsheetApp.openById('SHEET ID');
var tab = sheet.getSheetByName('Data');
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
var startRow = sheet.getLastRow();
var dataRange = tab.getRange(startRow,1,csvData.length,
csvData[0].length).setValues(csvData);
}
function importCSVFromGmail() {
var threads = GmailApp.search("Gmail Search");
var message = threads[0].getMessages();
var attachment = message[message.length - 1].getAttachments()[1];
var sheet = SpreadsheetApp.openById('SHEET ID');
var tab = sheet.getSheetByName('Data');
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
let o = csvData.map(r => {
let x = r.slice();
x.push(new Date());
return x;
}})
var startRow = sheet.getLastRow();
tab.getRange(startRow, 1, o.length, o[0].length).setValues(o);
}

Copy value to another sheet with a condition

I feel like today I'm not able to do anything with my script.
I'm trying to do a simple test, if the date in cell1 is equal to the date in cell2 then I will copy and paste the data into another file, in a specific sheet. If cell1 is different than cell2, I will copy the data in the same other file but in a different sheet.
I can't make it work. What am I doing wrong? thanks for the help,
j.
function copytransactionTodispatchN() {
var sss = SpreadsheetApp.getActiveSpreadsheet();; // sss = source spreadsheet
var ss = sss.getSheetByName("Nouveau Client - Transaction du jour"); // ss = source sheet
var ssn = sss.getSheetByName("Nouveau Client"); // ss = source sheet
//Get full range of data
var SRange = ss.getRange('A2:f2');
var SData = SRange.getValues();
var dateachat = ssn.getRange('c20').getValues;
var datelivraison = ssn.getRange('e31').getValues;
if(dateachat == datelivraison){
var tss = SpreadsheetApp.openById("idoftheotherfile"); // tss = target spreadsheet
var ts = tss.getSheetByName("sheet1"); // ts = target sheet
ts.getRange("b"+(getLastDataRow(ts)+1)+":i"+(getLastDataRow(ts)+1)).setValues(SData);
}
else {var tss = SpreadsheetApp.openById("idoftheotherfile"); // tss = target spreadsheet
var ts1 = tss.getSheetByName("Sheet2"); // ts = target sheet
//set the target range to the values of the source data
ts1.getRange("a"+(getLastDataRow(ts)+1)+":h"+(getLastDataRow(ts)+1)).setValues(SData);
}
}
function getLastDataRowN(sheet) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange("b" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}
Ok, the mistakes were :
getlastrow function was not working for condition 2
the test of the date was not woking, I had to replace if(dateachat == datelivraison.) by if(dateachat.valueOf() == datelivraison.valueOf())
And now it is all good. Thank you all!!
var sss = SpreadsheetApp.getActiveSpreadsheet();; // sss = source spreadsheet
var ss = sss.getSheetByName("Nouveau Client - Transaction du jour"); // ss = source sheet
var ssn = sss.getSheetByName("Nouveau Client"); // ss = source sheet
//Get full range of data
var SRange = ss.getRange('A2:h2');
var SData = SRange.getValues();
var dateachat = ssn.getRange('c20').getValues;
var datelivraison = ssn.getRange('e31').getValues;
if(dateachat.valueOf() == datelivraison.valueOf()){
var tss = SpreadsheetApp.openById("IDtarget"); // tss = target spreadsheet
var ts = tss.getSheetByName("Sheet1"); // ts = target sheet
ts.getRange("b"+(getLastDataRowb(ts)+1)+":i"+(getLastDataRowb(ts)+1)).setValues(SData);
}
else {var tss = SpreadsheetApp.openById("IDtarget"); // tss = target spreadsheet
var ts = tss.getSheetByName("Sheet 2"); // ts = target sheet
//set the target range to the values of the source data
ts.getRange("a"+(getLastDataRowa(ts)+1)+":h"+(getLastDataRowa(ts)+1)).setValues(SData);
}
}
function getLastDataRowb(sheet) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange("b" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}
function getLastDataRowa(sheet) {
var lastRow = sheet.getLastRow();
var range = sheet.getRange("a" + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
}```
var dateachat = ssn.getRange('c20').getValues;
Variable ssn isn't defined anywhere, which is likely causing dateachat to be undefined or null.

Exception: This action would increase the number of cells in the workbook above the limit of 10000000 cells

I have the following code but I'm getting the following error after running it.
Is there any way to resolve this?
The data that I'm retrieving has about that amount of cell but it may be retrieving blank rows but all the rows has formulas.
N# of rows per file:
uno: 72850
dos: 72850
tres: 72850
cuatro: 72850
cinco: 72850
Total: 364250
function test() {
var dest = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var ss = SpreadsheetApp.openById('id2')
var sh = ss.getSheetByName('uno')
var values = sh.getRange('A1:AF'+sh.getLastRow()).getValues()
dest.getRange(dest.getLastRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id2')
var sh = ss.getSheetByName('dos')
var values = sh.getRange('A1:AF'+sh.getLastRow()).getValues()
dest.getRange(dest.getLastRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id3')
var sh = ss.getSheetByName('tres')
var values = sh.getRange('A1:AF'+sh.getLastRow()).getValues()
dest.getRange(dest.getLastRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id4')
var sh = ss.getSheetByName('cuatro')
var values = sh.getRange('A1:AF'+sh.getLastRow()).getValues()
dest.getRange(dest.getLastRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id5')
var sh = ss.getSheetByName('cinco')
var values = sh.getRange('A1:AF'+sh.getLastRow()).getValues()
dest.getRange(dest.getLastRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
};
The error message seems to be related to current Spreadsheets limits in Google Sheets as #Cooper mentioned, currently the limit is the following:
​Up to 10 million cells or 18,278 columns (column ZZZ) for spreadsheets that are created in or converted to Google Sheets.
Creating a new sheet could do the work as the limits apply per sheets.
Try to replace getLastRow() by getLastDataRow() after adding
Object.prototype.getLastDataRow = function(col){
var lastRow = this.getLastDataRow();
if (col == null){col='A'}
var range = this.getRange(col + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
};
so ...
function test() {
var dest = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var ss = SpreadsheetApp.openById('id2')
var sh = ss.getSheetByName('uno')
var values = sh.getRange('A1:AF'+sh.getLastDataRow()).getValues()
dest.getRange(dest.getLastDataRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id2')
var sh = ss.getSheetByName('dos')
var values = sh.getRange('A1:AF'+sh.getLastDataRow()).getValues()
dest.getRange(dest.getLastDataRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id3')
var sh = ss.getSheetByName('tres')
var values = sh.getRange('A1:AF'+sh.getLastDataRow()).getValues()
dest.getRange(dest.getLastDataRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id4')
var sh = ss.getSheetByName('cuatro')
var values = sh.getRange('A1:AF'+sh.getLastDataRow()).getValues()
dest.getRange(dest.getLastDataRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
var ss = SpreadsheetApp.openById('id5')
var sh = ss.getSheetByName('cinco')
var values = sh.getRange('A1:AF'+sh.getLastDataRow()).getValues()
dest.getRange(dest.getLastDataRow()+1,1,values.length,values[0].length).setValues(values)
SpreadsheetApp.flush();
};
Object.prototype.getLastDataRow = function(col){
var lastRow = this.getLastDataRow();
if (col == null){col='A'}
var range = this.getRange(col + lastRow);
if (range.getValue() !== "") {
return lastRow;
} else {
return range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow();
}
};

Copying range of values from Google Sheet to other

I want to copy the range of values from one spreadsheet to another (A1:H45). I tried the code below. In spite of copying the values of Cells A1:H45, its copying A1 Cell data in a new sheet throughout A1:H45, which means the same data getting copied 45 times.
function Copy()
{
var sss = SpreadsheetApp.openById('1IK6YsZS3_NNAlFA41d8uKriPzfZs_2Ukyh94eeBFj40');
var ss = sss.getSheetByName('CURRENT');
var range = ss.getRange('A1:H45');
var data = range.getValues();
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName("New sheet");
if (yourNewSheet != null)
{
activeSpreadsheet.deleteSheet(yourNewSheet);
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName("Name of your new sheet");
yourNewSheet.getRange(yourNewSheet.getLastRow()+1,1,45,8).setValue(data);
}
Try this -
function Copy()
{
var sss = SpreadsheetApp.openById('1IK6YsZS3_NNAlFA41d8uKriPzfZs_2Ukyh94eeBFj40');
var ss = sss.getSheetByName('CURRENT');
var range = ss.getRange('A1:H45');
var data = range.getValues();
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var yourNewSheet = activeSpreadsheet.getSheetByName("New sheet");
if (yourNewSheet != null)
{
activeSpreadsheet.deleteSheet(yourNewSheet);
}
yourNewSheet = activeSpreadsheet.insertSheet();
yourNewSheet.setName("Name of your new sheet");
yourNewSheet.getRange(yourNewSheet.getLastRow()+1,1,45,8).setValues(data);
}
Your code is perfect. All you had to do was use setValues (plural) instead of setValue :)