Copying range of values from Google Sheet to other - google-apps-script

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 :)

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

How Can I Change My Range to Include Merged Cells?

I am trying to copy and paste "A4:J4" and "A5:H5" but I am getting an error because A5 is merged. Also "STAGE 3" only pastes in "G4" in Sheet2. How can I copy and paste this data to Sheet2 with merged cells?
function hi()
{
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var yourRange = sheet.getRange("A4");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var destSheet = ss.getSheetByName('Sheet2');
var yourLastColumn=sheet.getRange("A4:4").getLastColumn();
var range = ss.getRangeByName("A4");
var yourLastRange=sheet.getRange("A4").offset(0, yourLastColumn-1);
var rsltRange1 = yourLastRange.getNextDataCell(SpreadsheetApp.Direction.PREVIOUS);
var rsltRange2 = sheet.getRange("A4:" + rsltRange1.getA1Notation());
if (rsltRange2.isPartOfMerge()) {
var rangeTest = rsltRange2.getMergedRanges()[0];
} else {
}
Logger.log(rangeTest.getA1Notation());
var destRange = destSheet.getRange("A4");
rsltRange2.copyTo(destRange, {contentsOnly: false});
}
Here is a simplified version of your code that should copy your range correctly no matter if the range is merged or not:
function hi(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var destSheet = ss.getSheetByName('Sheet2');
var startColumn=1;
var startRow=4;
var numRows=2;
var numColumns=sheet.getLastColumn()-startColumn+1;
var range=sheet.getRange(startRow, startColumn, numRows, numColumns);
var destRange = destSheet.getRange("A4");
range.copyTo(destRange);
}

Renaming a file in google sheet to previous month name using 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".

Appending multiple rows from a source sheet to a destination sheet in Google Sheets

I am using code from this older thread to copy a range of cells from a source sheet and paste them to the last row of a destination sheet.
https://support.google.com/docs/forum/AAAABuH1jm04B0WxqiEJns/?hl=en&gpf=%23!topic%2Fdocs%2F4B0WxqiEJns
The suggested code copies and pastes the data on the same sheet so I attempted (and failed) to modify it:
function appendEagleData() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Eagle New Rows");
var dest = ss.getSheetByName("Eagle Static Data")
var source = sh.getRange("A4:J20");
var v = source.getValues();
dest.getRange(dest.getLastRow() + 1, 1, v.length, v[0].length).setValues(v);
}
...Clearly, I'm a little out of my depth. Any help would be appreciated.
function appendEagleData() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName("Eagle New Rows");
var rg1=sh1.getRange(4,1,sh1.getLastRow()-3,10);
var sh2=ss.getSheetByName("Eagle Static Data")
var rg2=sh2.getRange(sh2.getLastRow()+1,1);
rg1.copyTo(rg2);
}
try this:
function appendEagleData() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName("Eagle New Rows");
var rg1=sh1.getRange(4,1,getColumnHeight(2,sh1,ss)-3,10);
var sh2=ss.getSheetByName("Eagle Static Data")
var rg2=sh2.getRange(sh2.getLastRow()+1,1);
rg1.copyTo(rg2);
}
function getColumnHeight(col,sh,ss){
var ss=ss || SpreadsheetApp.getActive();
var sh=sh || ss.getActiveSheet();
var col=col || sh.getActiveCell().getColumn();
var rg=sh.getRange(1,col,sh.getLastRow(),1);
var vA=rg.getValues();
while(vA[vA.length-1][0].length==0){
vA.splice(vA.length-1,1);
}
return vA.length;
}

One function for multiple sheets in Google Sheets

in Google Sheets I have to repeat a function because getSheetByName() does not accept an array of sheets, it only accepts one sheet.
Is there a way to have one function that loops through specified sheets (not all sheets)?
i.e.
("Sheet1", "Sheet2" ) etc.
function recordHistory_1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var source = sheet.getRange("A2:B2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
};
function recordHistory_2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet2");
var source = sheet.getRange("A2:B2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
};
Reason I'm asking is because I have over 20 sheets, and so I have to write this function 20 times...
You can generalize / reuse the same function for 20 different calls as follows.
var sheetListArray = ["Sheet1", "Sheet2", "Sheet3"......"Sheet20"]
var ss = SpreadsheetApp.getActiveSpreadsheet();
for( var i = 1 ; i <= sheetListArray.length ; i++)
// You can call the below function 20 time with different Sheet name each time.
recordHistory(sheetListArray[i]);
}
function recordHistory(sheetName) {
var sheet = ss.getSheetByName(sheetName);
var source = sheet.getRange("A2:B2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
}
You can also call the function once and loop through an array of sheetnames inside the function.
function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
["Sheet1", "Sheet2", "Sheet3"].forEach(function (s) {
var sheet = ss.getSheetByName(s);
var values = sheet.getRange('A2:B2').getValues()
values[0][0] = new Date();
sheet.appendRow(values[0]);
})
}