How do you use a cell value to find the matching sheet name? - google-apps-script

I am trying to find a way to copy information from one sheet to another. I know how to find the information from the sheet to copy from, but I'm having trouble finding the sheet to copy to. I want to copy to a sheet based off of a value in my original sheet.
I have a list of names in column C, ex. John, Mark, and Will that starts in row 40. I would like to then copy John's row of information to the sheet titled "John", and Mark's information to a sheet titled "Mark", etc. so that each person's information is summarized on their own sheet. I am having trouble using the value found in column C (the person's name), and then using that value to find a sheet with the coordinating name.
function CopyInfo() {
var CopyFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Summary");
var ColumntoSearch = 3;
var LastRow = CopyFrom.getLastRow();
//Gets column to search for names to compare
var Range = CopyFrom.getRange(40, ColumntoSearch, LastRow, 1);
var Values = Range.getValues();
//Sets the amount of data to copy over
var NumberofColumns = 11;
var NumberofRows = 1;
//Compares all the names in the Summary sheet
var d=0;
for(var i=0;i<Values.length;i++) {
var Name = CopyFrom.getRange(i-d+40, 3);
var CopyTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Name);
if(Name == ????????){
var RangetoCopy=CopyFrom.getRange(i-d+40,1,NumberofRows,NumberofColumns);
var DestRange=CopyTo.getRange(CopyTo.getLastRow()+1,1,NumberofRows,NumberofColumns);
RangetoCopy.copyTo(DestRange);
d++;
}
}
}

You want to copy the values from Summary sheet to each sheet with the sheet name retrieved from the column "C" in Summary sheet.
There are values for copying in the column "A:K".
For example, when the row 45 of Summary sheet has the values of a45, b45, c45, d45, e45, f45, g45, h45, i45, j45, k45, the values are copied to just below the last row of the sheet name of c45.
If my understanding is correct, how about this modification? I think your script is almost correct. So I modified your script a little.
Modified script:
function CopyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Added
var CopyFrom = ss.getSheetByName("Summary"); // Modified
var ColumntoSearch = 3;
var LastRow = CopyFrom.getLastRow();
//Gets column to search for names to compare
var Range = CopyFrom.getRange(40, ColumntoSearch, LastRow, 1);
var Values = Range.getValues();
//Sets the amount of data to copy over
var NumberofColumns = 11;
var NumberofRows = 1;
//Compares all the names in the Summary sheet
// var d=0; // Removed
for (var i = 0; i < Values.length; i++) {
var Name = Values[i][0]; // Modified
var CopyTo = ss.getSheetByName(Name); // Modified
if (Name) { // Modified
if (!CopyTo) CopyTo = ss.insertSheet(Name); // Added
var RangetoCopy = CopyFrom.getRange(i + 40, 1, NumberofRows, NumberofColumns); // Modified
var DestRange = CopyTo.getRange(CopyTo.getLastRow() + 1, 1, NumberofRows, NumberofColumns);
RangetoCopy.copyTo(DestRange);
// d++; // Removed
}
}
}
Note:
In this modified script, if the sheet name is not found, new sheet of the sheet name is inserted. If you don't want to insert new sheet, please replace if(!CopyTo) CopyTo = ss.insertSheet(Name) to the following script.
if (CopyTo) {
var RangetoCopy = CopyFrom.getRange(i + 40, 1, NumberofRows, NumberofColumns);
var DestRange = CopyTo.getRange(CopyTo.getLastRow() + 1, 1, NumberofRows, NumberofColumns);
RangetoCopy.copyTo(DestRange);
}
If I misunderstood your question and this was not the result you want, I apologize.

Related

Copying data from a sheet to another with conditions

I have been trying to copy some data from a sheet to another but I have been running into some trouble.
I have to copy data and stop copying until the scripts finds an empty space, and I have to paste this data into another sheet where there's blank space (available space).
This is the code I have so far:
function copyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("sheet1");
var pasteSheet = ss.getSheetByName("sheet2");
var source = copySheet.getRange(11,1,1,10);
var destination = pasteSheet.getRange(1,1,1,10);
for (i = 1; i < 20; i++) {
if (destination.isBlank() == true) {
destination = pasteSheet.getRange(i, 1, 1, 10);
source = copySheet.getRange(i + 10, 1, 1, 10);
source.copyTo(destination);
} else {
destination = pasteSheet.getRange(i, 1, 1, 10);
}
}
}
It recognizes that the destination has an empty space, although it doesn't really paste it. The for (i = 1; i <20; i++) is for testing purposes.
If your data doesn't have any blank rows in between the first row and last non-empty row, then you can use this:
Sample Data:
sheet1
sheet2
Script:
function copyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("sheet1");
var pasteSheet = ss.getSheetByName("sheet2");
// get last rows of each sheet
var sLastRow = copySheet.getLastRow();
var dLastRow = pasteSheet.getLastRow();
// get data from sheet1 from row 11 to last row
var source = copySheet.getRange(11,1,sLastRow - 10,10).getValues();
// paste data to sheet2's last row
pasteSheet.getRange(dLastRow + 1,1,source.length,source[0].length).setValues(source);
}
Output:
Alternative:
If you have blank rows in between your sheet1, you can filter the values in sheet1.
Sample Data:
blank row 13 in sheet1
function copyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("sheet1");
var pasteSheet = ss.getSheetByName("sheet2");
// get last rows of each sheet
var sLastRow = copySheet.getLastRow();
var dLastRow = pasteSheet.getLastRow();
// get data from sheet1 from row 11 to last row
// exclude rows with blank values in all columns
var source = copySheet.getRange(11,1,sLastRow - 10,10).getValues()
.filter(row => row.filter(col => !col).length < row.length);
// paste data to sheet2's first blank row
pasteSheet.getRange(dLastRow + 1,1,source.length,source[0].length).setValues(source);
}
Output:

Google Script: copy values from one sheet to another determining the range

I have two sheets with unique IDs in one column. I need to make sure whenever a new ID is added in one sheet (Sheet1), it is copied to the last empty row in the other sheet (Sheet2). The IMPORTRANGE won't work as being dynamic any static information added in the other sheet would be irrelevant to the respective ID.
In another thread [1], I got help developing this script that will do exactly that. However, this script will insert the data in the other sheet in Column A. How can I modify the script so I can decide the specific range where I want the script to insert the data (in Sheet 2).
Update: I created this spreadsheet as an example. I'm trying to ensure that the script does the calculation (ie. adding vlaues that are not duplicated in the first available empty row), starting in cel C10 in "Sheet2". It would be also great if I can somehow change that range if I need to: https://docs.google.com/spreadsheets/d/1abESAXFrOHoqRQRNqQGfmAFxlbD10wlprAf1tca4y7o/edit#gid=132361488
Thanks!
function updateSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = "Sheet1";
var destinationSheet = "Sheet2";
var source_sheet = ss.getSheetByName(sourceSheet);
var target_sheet = ss.getSheetByName(destinationSheet);
var lastCol = target_sheet.getLastColumn();
var lastRow = target_sheet.getLastRow();
if (lastRow > 1) { // <--- Added
var r = target_sheet.getRange(2,1, lastRow - 1, lastCol);
r.sort([{column: 1, ascending: true}]);
}
_updateSpreadsheet(source_sheet, target_sheet);
}
function _updateSpreadsheet(source_sheet, target_sheet) {
var last_row = target_sheet.getLastRow();
var source_data = source_sheet.getRange("A4:A" + source_sheet.getLastRow()).getValues(); // <--- Modified
var target_data = target_sheet.getDataRange().getValues();
var resultArray = [];
for (var n = 0 ; n < source_data.length ; n++) { // <--- Modified
var keep = true;
for(var p in target_data) {
if (source_data[n][0] == target_data[p][0]) {
keep = false; break;
}
}
var columnsToKeep = [0];
var tempData = [];
if(keep){
for(var c in columnsToKeep){ tempData.push(source_data[n][columnsToKeep[c]])}
resultArray.push(tempData);
}
}
last_row++;
resultArray = resultArray.filter(String); // <--- Added
if(resultArray.length>0){
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length).setValues(resultArray);
}
}
[1] Google Script: Append new values in column to another sheet
target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length)
.setValues(resultArray);
This line
Takes the sheet stored in the variable target_sheet
Accesses the defined range
Sets values
The syntax to access a range used in your code is getRange(row, column, numRows, numColumns)
whereby the start column is numerical - in your case it's 1 which corresponds to column A.
If you want to modify the start column from A to B:
Just change your range definition from
getRange(last_row,1,resultArray.length,resultArray[0].length)
to
getRange(last_row,2,resultArray.length,resultArray[0].length)

Inserting cell values into this Google app script code for importing is not working

I am writing a Google app script code so that csv data files can get imported to a Google spreadsheet automatically.
This is my code:
function myFunction() {
var file = DriveApp.getFilesByName("data.csv").next();
varcsvData = Utilities.parseCsv(file.getBlob().getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
var numrows = csvData.length();
var numcols = csvData[0].length();
sheet.getRange(1,1, numrows, numcols).setValue(csvData)
}
The code works fine with when importing all rows and columns. But it does not work when I specify a cell range like 'B2:C5'. I tried inserting values for numrows (for cell range B2:C5 - rows 5 cols 2) and numcols. The code runs but there is no output to be seen. i.e. no data import on google sheet with the specified cell range.
Can someone please help?
How about this modification?
Modification points:
Please modify length() to length.
Values retrieved by Utilities.parseCsv() is 2 dimensional array. In order to use this, please modify setValue(csvData) to setValues(csvData).
Modified script:
function myFunction() {
var file = DriveApp.getFilesByName("data.csv").next();
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
var numrows = csvData.length; // Modified
var numcols = csvData[0].length; // Modified
sheet.getRange(1,1, numrows, numcols).setValues(csvData); // Modified
}
Note:
In your script, the lengths for rows and columns are retrieved by numrows and numcols. So you can use them for the method of setValues().
References:
length
parseCsv(csv)
setValues(values)
If I misunderstood your question, I apologize. And if this didn't work for your situation, can you provide a sample CSV file? By this, I would like to confirm it.
Edit:
You want to put the values by selecting the ranges from the CSV values of the file.
If my understanding is correct, how about this sample script?
Pattern 1:
In this pattern, the GridRange is used for selecting the values from the range of CSV data. Values selected using the GridRange are put to the Spreadsheet.
Sample script:
function myFunction() {
// As a sample, C3:D5 is as follows.
var startRowIndex = 2;
var endRowIndex = 5;
var startColumnIndex = 2;
var endColumnIndex = 4;
var file = DriveApp.getFilesByName("data.csv").next();
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
var values = [];
for (var row = startRowIndex; row < endRowIndex; row++) {
var temp = [];
for (var col = startColumnIndex; col < endColumnIndex; col++) {
temp.push(csvData[row][col]);
}
values.push(temp);
}
var sheet = SpreadsheetApp.getActiveSheet();
var numrows = values.length;
var numcols = values[0].length;
sheet.getRange(1,1, numrows, numcols).setValues(values);
}
Pattern 2:
In this pattern, a1Notation is used for selecting the values from the range of CSV data. At first, all CSV data is put to Spreadsheet. Then, the values of the selected range are retrieved. The values are put to the Spreadsheet after the Spreadsheet is cleared.
Sample script:
function myFunction() {
var csvRange = "C3:D5"; // Please set the range of CSV data.
var file = DriveApp.getFilesByName("data.csv").next();
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
var numrows = csvData.length;
var numcols = csvData[0].length;
sheet.getRange(1,1, numrows, numcols).setValues(csvData);
var values = sheet.getRange(csvRange).getValues();
sheet.clearContents();
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}

COPYING DATA FROM ONE SPREADSHEET TO ANOTHER

I have three source files - Alpha, Beta, Kappa. They have same headers and basically, I just want them all consolidated in one file on a weekly basis. I started with Kappa and somehow it works - it creates a new spreadsheet and copies info from the Kappa file and paste it to the newly created spreadsheet as values.
Now I tried, adding the Alpha file to the same spreadsheet, just below the info that I copied from the Kappa file using the getLastRow function. I got an error saying that source range and target range must be on the same spreadsheet.
function RawExtractCopy() {
var version = 'ver. 4.01'
var ssnew = SpreadsheetApp.create('V5 Raw Extract '+ version ); //create a spreadsheet
var ssnewsheet = ssnew.getSheetByName('Sheet1'); //get the sheet named Sheet1
ssnewsheet.insertRows(1,30000); //inserting more rows
ssnewsheet.setName('V5 Raw Extract'); //rename the sheet name of the newly created spreadsheet
var ssKappa = SpreadsheetApp.getActiveSpreadsheet(); //opens source file
var targetss = ssnew; //define created ss as the target ss
var srcSheetKappa = ssKappa.getSheetByName('KAPPA'); //get source sheet name
var targetSheet = targetss.getSheetByName('V5 Raw Extract'); //defining target sheet
var srcRangeKappa = srcSheetKappa.getRange("A1:AM30000"); //get source data
var destRangeKappa = targetss.getRange("A1"); //define target
var values = srcRangeKappa.getValues(); //line 18 to 21 is just to match source sheet and target sheet
var bGcolors = srcRangeKappa.getBackgrounds();
var colors = srcRangeKappa.getFontColors();
var fontSizes = srcRangeKappa.getFontSizes();
destRangeKappa.setValues(values);
destRangeKappa.setBackgrounds(bGcolors);
destRangeKappa.setFontColors(colors);
destRangeKappa.setFontSizes(fontSizes);
srcRangeKappa.copyTo(destRangeKappa, {contentsOnly: true});
var ssAlpha = SpreadsheetApp.openById("1gIs4vCdcGG79poDujz9t8Fq7_BWlaEiMrYUH9DTxVHs").activate();
var srcSheetAlpha = ssAlpha.getSheetByName('V5 ALPHA');
var srcRangeAlpha = srcSheetAlpha.getRange("A2:AM30000");
var destRangeAlpha = targetSheet.getRange(targetSheet.getLastRow()+1,1);
var valuesAlpha = srcRangeAlpha.getValues();
var bGcolorsAlpha = srcRangeAlpha.getBackgrounds();
var colorsAlpha = srcRangeAlpha.getFontColors();
var fontSizesAlpha = srcRangeAlpha.getFontSizes();
destRangeAlpha.setValues(values);
destRangeAlpha.setBackgrounds(bGcolors);
destRangeAlpha.setFontColors(colors);
destRangeAlpha.setFontSizes(fontSizes);
srcRangeKappa.copyTo(destRangeAlpha, {contentsOnly: true});
}
The thing, it still copies the data from Kappa but did not push through with Beta. Can someone please be kind to tell what I am missing here?
The OP's goal is to make a duplicate of three sheets in three separate spreadsheets; Alpha, Beta and Kappa. The OP's code works for Kappa, but not Alpha or Beta.
Why does this code work and the OP code doesn't
Well, the OP code does work, but the OP fudges by specifying a fixed range (30000 rows long and about 40 column wide). This works for the first sheet, but not so easily for the second and third sheets. The following code differs in two major respects from the OP code:
the data ranges in Alpha, Beta, Kappa and "Raw Extract" are evaluated using getLastRow and getLastColumn. So the source range and the target range will match each other. In addition, data from the second and third sheets is easily appended one row below the preceding last row.
the copyTo code is changed to copy the whole sheet rather than a range. The reason for this is the the preceding four commands setValues(values), setBackgrounds(bGcolors), setFontColors(colors), and setFontSizes(fontSizes) have already copied the data range to "Raw Extract".
function so_55448299() {
var version = 'ver. 4.01'
var ssnew = SpreadsheetApp.create('V5 Raw Extract ' + version); //create a spreadsheet
var ssnewsheet = ssnew.getSheetByName('Sheet1'); //get the sheet named Sheet1
ssnewsheet.setName('V5 Raw Extract'); //rename the sheet name of the newly created spreadsheet
// copy Kappa and data
var ssKappa = SpreadsheetApp.getActiveSpreadsheet(); //opens source file
var targetss = ssnew; //define created ss as the target ss
var srcSheetKappa = ssKappa.getSheetByName('KAPPA'); //get source sheet name
var targetSheet = targetss.getSheetByName('V5 Raw Extract'); //defining target sheet
// get the last row and column of the source sheet
var kappaLastRow = srcSheetKappa.getLastRow();
var kappaLastCol = srcSheetKappa.getLastColumn();
//Logger.log("DEBUG: Kappa Last row = "+kappaLastRow+", Last column = "+kappaLastCol);//DEBUG
// declare the source and target ranges
var srcRangeKappa = srcSheetKappa.getRange(1, 1, kappaLastRow, kappaLastCol); //get source data
var destRangeKappa = targetSheet.getRange(1, 1, kappaLastRow, kappaLastCol); //define target
// get values and other data
var values = srcRangeKappa.getValues(); //line 18 to 21 is just to match source sheet and target sheet
var bGcolors = srcRangeKappa.getBackgrounds();
var colors = srcRangeKappa.getFontColors();
var fontSizes = srcRangeKappa.getFontSizes();
// set values and other data
destRangeKappa.setValues(values);
destRangeKappa.setBackgrounds(bGcolors);
destRangeKappa.setFontColors(colors);
destRangeKappa.setFontSizes(fontSizes);
// duplicate the entire sheet
srcSheetKappa.copyTo(targetss);
// end copy Kappa and data
// start copy Alpha and data
var ssAlpha = SpreadsheetApp.openById("<insert code here>");
var srcSheetAlpha = ssAlpha.getSheetByName('V5 ALPHA');
// get the last row and column of the source sheet
var alphaLastRow = srcSheetAlpha.getLastRow();
var alphaLastCol = srcSheetAlpha.getLastColumn();
//Logger.log("DEBUG: Alpha Last row = "+alphaLastRow+", Alpha Last Column = "+alphaLastCol);//DEBUG
// get the last row and column of the target sheet
var rawLastRow = targetSheet.getLastRow();
var rawLastCol = targetSheet.getLastColumn();
Logger.log("DEBUG: Target Last row = " + rawLastRow + ", Target Last Column = " + rawLastCol); //DEBUG
// declare the source and target ranges
var srcRangeAlpha = srcSheetAlpha.getRange(2, 1, alphaLastRow - 1, alphaLastCol);
var destRangeAlpha = targetSheet.getRange(rawLastRow + 1, 1, alphaLastRow - 1, alphaLastCol);
//Logger.log("DEBUG:destRangeAlpha = "+destRangeAlpha.getA1Notation());//DEBUG
// get values and other data
var values = srcRangeAlpha.getValues();
var bGcolors = srcRangeAlpha.getBackgrounds();
var colors = srcRangeAlpha.getFontColors();
var fontSizes = srcRangeAlpha.getFontSizes();
// set values and other data
destRangeAlpha.setValues(values);
destRangeAlpha.setBackgrounds(bGcolors);
destRangeAlpha.setFontColors(colors);
destRangeAlpha.setFontSizes(fontSizes);
// duplicate the entire sheet
srcSheetAlpha.copyTo(targetss);
// end copy Alpha and data
// start copy Beta and data
var ssBeta = SpreadsheetApp.openById("<insert code here>");
var srcSheetBeta = ssBeta.getSheetByName('V5 BETA');
// get the last row and column of the source sheet
var betaLastRow = srcSheetBeta.getLastRow();
var betaLastCol = srcSheetBeta.getLastColumn();
//Logger.log("DEBUG: Beta Last row = "+betaLastRow+", Beta Last Column = "+betaLastCol);//DEBUG
// get the last row and column of the target sheet
var rawLastRow = targetSheet.getLastRow();
var rawLastCol = targetSheet.getLastColumn();
//Logger.log("DEBUG: Target Last row = "+rawLastRow+", Target Last Column = "+rawLastCol);//DEBUG
// declare the source and target ranges
var srcRangeBeta = srcSheetBeta.getRange(2, 1, betaLastRow - 1, betaLastCol);
var destRangeBeta = targetSheet.getRange(rawLastRow + 1, 1, betaLastRow - 1, betaLastCol);
//Logger.log("DEBUG:destRangeBeta = "+destRangeBeta.getA1Notation());//DEBUG
// get values and other data
var values = srcRangeBeta.getValues();
var bGcolors = srcRangeBeta.getBackgrounds();
var colors = srcRangeBeta.getFontColors();
var fontSizes = srcRangeBeta.getFontSizes();
// set values and other data
destRangeBeta.setValues(values);
destRangeBeta.setBackgrounds(bGcolors);
destRangeBeta.setFontColors(colors);
destRangeBeta.setFontSizes(fontSizes);
// duplicate the entire sheet
srcSheetBeta.copyTo(targetss);
// end copy Beta and data
}
UPDATE - One Small Function
#tehhowch rightly observes that a more appropriate way to manage this process would be one small function called with a few parameters from a driver function. This is something that I had in mind at the time but (for better or worse) I felt that the long-hand approach would enable the OP to better understand how the code varied from their own. However, this variation seeks to fulfil tehhowch's observation. I have left in the Logger statements for the benefit of the OP (which explains the extraordinary length of the code
function so_55448299_04() {
//Note#1: this function assumes that it is located in the "Kappa" sheet
//Note#2: the spreadsheet ID for Alpha and Beta cannot be assigned to a variable. they must be entered longhand BEFORE this function is processed.
//Note#3: the target sheet names are also entered longhand. BUT the number of sheets is described in the variable "usersheets"
// user defined variables
var targetVn = 'ver. 4.01';
var targetName = 'V5 Raw Extract';
var usersheets = 3;
// create the targetspreadsheet and starting sheet
var targetss = SpreadsheetApp.create(targetName + " " + targetVn);
var targetSheet = targetss.getSheetByName('Sheet1');
targetSheet.setName(targetName);
//loop through the usersheets
for (var i = 0; i < usersheets; i++) {
// if i==0, then process this sheet - KAPPA
if (i == 0) {
//Logger.log("DEBUG: This is KAPPA");//DEBUG
var srcss = SpreadsheetApp.getActiveSpreadsheet();
//Logger.log("DEBUG: this spreadsheet is "+srcss.getName());//DEBUG
// startrow is 1 in order to include headers
var startrow = 1;
var srcSheet = srcss.getSheetByName("v5 KAPPA");
}
// if i=1, then process Alpha
else if (i == 1) {
//Logger.log("DEBUG: This is ALPHA");//DEBUG
var srcss = SpreadsheetApp.openById("<Insert code>");
//Logger.log("DEBUG: this spreadsheet is "+srcss.getName());//DEBUG
// startrow is 2 in iorder to avoid duplicating headers
var startrow = 2;
var srcSheet = srcss.getSheetByName("v5 ALPHA");
}
// if i=2, then process Beta
else if (i == 2) {
//Logger.log("DEBUG: This is BETA");//DEBUG
var srcss = SpreadsheetApp.openById("<Insert code>");
//Logger.log("DEBUG: this spreadsheet is "+srcss.getName());//DEBUG
// startrow is 2 in iorder to avoid duplicating headers
var startrow = 2;
var srcSheet = srcss.getSheetByName(usersheets[i]);
}
// run the subroutine to copy and paste data
// Logger.log("DEBUG: srcSheet: "+srcSheet.getName()+", targetSheet: "+targetSheet.getName()+", startrow: "+startrow+", targetss: "+targetss.getName());//DEBUG
var getresult = getData04(srcSheet, targetSheet, startrow, targetss);
}
}
function getData04(srcSheet, targetSheet, startrow, targetss) {
//get the source sheet - last row and column
var srcLastRow = srcSheet.getLastRow();
var srcLastCol = srcSheet.getLastColumn();
//Logger.log("DEBUG: Source Last row = "+srcLastRow+", Last column = "+srcLastCol);//DEBUG
// get the target sheet - last row and column
var targetLastRow = targetSheet.getLastRow();
var targetLastCol = targetSheet.getLastColumn();
//Logger.log("DEBUG: Target Last row = "+targetLastRow+", Target Last Column = "+targetLastCol);//DEBUG
// declare the source and target ranges
if (startrow == 1) {
var srcRange = srcSheet.getRange(startrow, 1, srcLastRow, srcLastCol);
var targetRange = targetSheet.getRange(startrow, 1, srcLastRow, srcLastCol);
} else {
var srcRange = srcSheet.getRange(startrow, 1, srcLastRow - 1, srcLastCol);
var targetRange = targetSheet.getRange(targetLastRow + 1, 1, srcLastRow - 1, srcLastCol);
}
//Logger.log("DEBUG: srcRange = "+srcRange.getA1Notation()+", target range = "+targetRange.getA1Notation());//DEBUG
// get source values and other data
var values = srcRange.getValues();
var bGcolors = srcRange.getBackgrounds();
var colors = srcRange.getFontColors();
var fontSizes = srcRange.getFontSizes();
// set values and other data
targetRange.setValues(values);
targetRange.setBackgrounds(bGcolors);
targetRange.setFontColors(colors);
targetRange.setFontSizes(fontSizes);
// duplicate the entire sheet
srcSheet.copyTo(targetss);
var result = "Successful";
return result;
}

Copying Rows of Data to Different Sheets

I am new to coding/JavaScript, so I apologize in advance if this question is (unintentionally) poorly phrased. I've been searching around and found some similar questions but nothing to solve my issue.
I have a scenario where I have a Workbook with one sheet called "Data" containing records and a column header. There is another sheet called "Template" containing a fixed template. I need to duplicate the Template for the number of records in Data (i.e. 5 records of Data will create 4 copies of the original Template). Next, I need to add the first record in Data to a specific cell range in the original Template, the second record in Data to the same specific cell range in the first Template copy, etc.
I've gotten my script to where I can duplicate the Template sheet and pull all the records into an array, but I haven't been able to figure out how to set the first record to the original Template, the second record to the second Template, etc. Any help is greatly appreciated!
function duplicate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
var startRow = 2; //first row
var lastRow = sheet.getLastRow();
var StartCol = 1
var LastCol = sheet.getLastColumn()
var numCol = sheet.getLastColumn();
var numRows = sheet.getLastRow(); // Number of rows to process
var dataRange = sheet.getRange(startRow, StartCol, numRows, numCol);
var data = dataRange.getValues();
//Duplicate Sheet based on # of Records
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("Template");
for (i=1;i<numRows;++i) s.copyTo(ss).setName("Template "+i);
//A bad attempt at trying to add the records to each template copy
var nextSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template "+i);
nextSheet.getRange(lastRow+1,1,numRows,numCol).setValues(data[0+1]);
}
'
If I understand correctly, you would like each data record[row] to have its own sheet, based on a Template, with the single record inserted into the same cell range for each record's individual sheet?
function duplicate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Data");
// Get the Template sheet
var template = ss.getSheetByName("Template");
var startRow = 2; //first row
var lastRow = sheet.getLastRow();
var StartCol = 1;
var LastCol = sheet.getLastColumn();
var numCol = sheet.getLastColumn();
var numRows = sheet.getLastRow(); // Number of rows to process
var dataRange = sheet.getRange(startRow, StartCol, numRows, numCol);
var data = dataRange.getValues();
// The constant single column range to insert the data record into
var data_insert_range = sheet.getRange("C14:C22").getA1Notation();
// For each data record create a new sheet based on the template
// and insert into a pre-set range
data.forEach(function (e,i) {
var nextSheet = ss.insertSheet("Template Copy " + i, {template: template});
// Map each col of the record into it's own row
var dataRowIntoCol = e.map(function (c) { return [c] });
// Insert record into the desired column
nextSheet.getRange(data_insert_range).setValues(dataRowIntoCol);
});
}
Instead of using the template to both copy from and overwriting data, I would suggest keeping the Template pure and create new sheets for writing data from it. If not, just place your copyTo() back in place of the insertSheet() and it will work that way as well
edit: Updated code to reflect clarified range/data information
I wasn't sure exactly what you wanted but I think this will give you a boost in a positive direction.
function duplicate() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var sheet=ss.getSheetByName('Data');
var startRow = 2; //first row
var lastRow = sheet.getLastRow();
var StartCol = 1
var LastCol = sheet.getLastColumn()
var numCol = sheet.getLastColumn();
var numRows = sheet.getLastRow()-startRow+1; // Number of rows to process
var dataRange = sheet.getRange(startRow, StartCol, numRows, numCol);
var data = dataRange.getValues();
//Duplicate Sheet based on # of Records
var s = ss.getSheetByName("Template");
for (i=0;i<numRows;++i)
{
s.copyTo(ss).setName("Template " + Number(i+1));
s.getRange(startRow,startCol,numRows,numCol).setValues(data);
}
}