I have a script that allows me to import data from a multitude of "child" spreadsheets to a "parent" spreadsheet.
Each child is composed of many tabs, but all the data that I import is unified thanks to queries in a single sheet of the child ("datasheet").
Problem is: if in the future I want to modify something (for example import more data from the childs), i would then have to go and edit manually every single child datasheet.
I'd rather have a script that would do the following:
In my "Parent", i would create a "datasheet" which would be the template datasheet.
The script would copy the "content" (and the formulas) of the parent datasheet.
It would paste this content+formulas in all the spreadsheets specified (in my Parent, i already have a list of URLs - one for each child).
I don't want to "copy" the parent datasheet, i'd rather replace content.
Is this even possible?
Thank you in advance for your help!
Based on our conversation on comments, I comprehend that you want to copy all data from the Parent sheet into the specified sheets. I'll assume that the list of sheets is located in the upper left corner of the Parent sheet. If that isn't the case, please forgive me and indicate to me where the sheet list is located. This is the code that fulfills your request:
function sheetPopulator(spreadsheetID) {
var masterSheet = SpreadsheetApp.openById(spreadsheetID).getSheetByName(
"Parent");
var specifiedSheets = masterSheet.getRange(2, 1, masterSheet.getLastRow(), 1)
.getValues();
var lastRowMasterSheet = masterSheet.getLastRow();
var lastColumnMasterSheet = masterSheet.getLastColumn();
var allData = masterSheet.getRange(1, 1, masterSheet.getLastRow(), masterSheet
.getLastColumn()).getValues();
for (var i = 0; i < specifiedSheets.length; i++) {
if (SpreadsheetApp.openById(spreadsheetID).getSheetByName(specifiedSheets[
i]) != null) {
SpreadsheetApp.openById(spreadsheetID).getSheetByName(specifiedSheets[i])
.getRange(1, 1, lastRowMasterSheet, lastColumnMasterSheet).setValues(
allData);
}
}
}
That function will first gather the list of specified sheets and after that will read all the data from the Parent sheet. After that, the code will iterate over every element of the list and, if that element coincides with a sheet name, it will copy all the previously read data into that sheet.
Please, take this as one of many possible solutions to your issue. Don't hesitate to ask me for clarifications or further help.
UPDATE
I apologize if the previous script doesn't fulfill your requests. After reading your new comments I studied your spreadsheets and designed a new code. I have tested this new script on copies of your spreadsheets and it works flawlessly. This is the code in question:
function sheetPopulatorII() {
var parentSheetID = "{PARENT SHEET ID}";
var childrenListSheet = SpreadsheetApp.openById(parentSheetID).getSheetByName(
"Childs");
var childrenList = childrenListSheet.getRange(2, 1, childrenListSheet
.getLastRow() - 1, 1).getValues();
for (var i = 0; i < childrenList.length; i++) {
childrenList[i][0] = childrenList[i][0].toString().substring(39, 83);
}
for (var i = 0; i < childrenList.length; i++) {
var children = SpreadsheetApp.openById(childrenList[i][0]);
children.getSheets()[0].setName("OLD SHEET");
SpreadsheetApp.openById(parentSheetID).getSheetByName("Master").copyTo(
children).setName("Data");
children.deleteSheet(children.getSheetByName("OLD SHEET"));
}
}
I am going to explain this code step by step. First, it opens the children list sheet (inside the Parent Sheet) using .openById() for opening the Parent spreadsheet, .getSheetByName() to open the involved sheet, .getRange() for selecting the list, .getLastRow() to know how long the list is (so you can add new URLs on the future using the same code) and .getValues() to gather the data.
Afterwards the code will iterate the list to convert the URLs into IDs with .substring() to cut away the non-ID parts. Next, it will iterate the list again but this time it will rename the old sheet with a temporal name using .setName(), copy the Parent sheet with .copyTo() and delete the renamed sheet with .deleteSheet(). This approach copy both: values and formulas. Please, contact me again if you need further help developing the code or understanding it.
Related
My first issue is this, I have an items log sheet where I want to add and manage individual unique items in our inventory. I created a data validation dependent dropdown list for a main category and found out how to build a script to dynamically create a secondary category dropdown list based on the selected main category.
For Example:
If cell B2 (Main Category) is set to Carabiner (based on data validation range on another sheet) THEN cell C2 (secondary Category) will dynamically create a dropdown list relative to the Carabiner main category (i.e. locking, non-locking)
That is simple enough if you only have one row to create the dropdown lists, but I wanted to be able to pick from a secondary category list in each row dependent on which was picked in the main category cell.
I found a video of a script that did just that and got it working just fine.
Now the problem is that the script runs data validation on every other sheet. How can I limit the script to only run on a specific sheet?
Here is the script:
function onEdit() {
// this line just refers to the current file var start = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var current = start.getActiveCell()
// var to refer to the worksheets -lists is where the data validation range will come from, and main is where we want to use that data validation range var list = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Indirect_Categ_Ranges") var main = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Items_Log");
// has the user selected a category? Refers to the column number in the Items_Log sheet where the user has picked the main category
if (current.getColumn()==2)
{
//to copy the selected sub-category -the 2,1 is the row and column on the Indirect_Categ_Ranges sheet where this script will dynamically update the main category picked to define what the indirect function will display in the next column
var choice = current.getValue()
list.getRange(2,1).setValue(choice)
//clear any validation -the 2,3,1000 looks to start clearing validation at row 2, column 3 and down for up to 1000 entries
main.getRange(2,3,5000).clearDataValidations()
// create the rule - var_point defines the offset number of rows and columns to shift to initiate the dynamic dependent dropdown list, the var_items defines where the to look for the range to build the dropdown list
var point = current.offset(0,1)
var items = list.getRange(2,2,50)
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(items,true).build();
point.setDataValidation(rule)
}
}
Also, is there a way to have the clear validations to run no matter how many rows there are?
The function will run anytime there's an edit and there's nothing you can do to stop that. You can, instead, terminate execution preemptively if it's not the sheet you care about.
The event object tells you which range was edited. You can get that range's sheet to know which sheet was edited. If the name matches, then execute the other stuff.
function onEdit(e) {
if (e.range.getSheet().getName() === 'Items_Log') {
// Data validation
}
}
It's not great practice to use .getActiveRange() or .getActiveSheet() when you want what was actually edited because there is a chance, however small, that the edited range may differ from the active range at the time of function execution.
Explanation:
You need to take advantage of the event object.
That object contains relevant information to the edits you make.
For example:
e.source is equivalent to SpreadsheetApp.getActive()
e.range is equivalent to .getActiveCell().
To run the code only for a particular sheet, in this case Items_Log, add a condition to check if the name of the active sheet matches that name:
if (current.getColumn()==2 && start.getName()=="Items_Log")
where start is the active sheet:
var start = e.source.getActiveSheet();
Solution:
function onEdit(e) {
var start = e.source.getActiveSheet();
var current = e.range;
var list = e.source.getSheetByName("Indirect_Categ_Ranges")
var main = e.source.getSheetByName("Items_Log");
if (current.getColumn()==2 && start.getName()=="Items_Log")
{
var choice = current.getValue()
list.getRange(2,1).setValue(choice)
main.getRange(2,3,5000).clearDataValidations()
var point = current.offset(0,1)
var items = list.getRange(2,2,50)
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(items,true).build();
point.setDataValidation(rule)
}
}
Thanks for the help. after looking at your suggestions and trying a couple things, I found that simply adding the code:
&& start.getName()=="Items_Log")
To the end of the line:
if (current....
Worked and solved the issue.
I have a google sheet with around 190 tabs on that i need to split into 190 different files
The files need to be named the same as the tab, the contents of the tab need to be copied as values but i also need to bring the formatting accross (just not the formulas).
I have looked around, and through a combination of previous questions and answers plus using the function list help have formed the following code. It actually works for the first few tabs but then throws up an error about being unable to delete the only sheet.
function copySheetsToSS() {
var ss = SpreadsheetApp.getActive();
for(var n in ss.getSheets()){
var sheet = ss.getSheets()[n];// look at every sheet in spreadsheet
var name = sheet.getName();//get name
if(name != 'master' && name != 'test'){ // exclude some names
var alreadyExist = DriveApp.getFilesByName(name);// check if already there
while(alreadyExist.hasNext()){
alreadyExist.next().setTrashed(true);// delete all files with this name
}
var copy = SpreadsheetApp.create(name);// create the copy
sheet.copyTo(copy);
copy.deleteSheet(copy.getSheets()[0]);// remove original "Sheet1"
copy.getSheets()[0].setName(name);// rename first sheet to same name as SS
var target_sheet = copy.getSheetByName(name);
var source_range = sheet.getRange("A1:M50");
var target_range = target_sheet.getRange("A1:M50");
var values = source_range.getValues();
target_range.setValues(values);
}
}
}
I am hoping someone can tell me what i have done wrong as I cannot figure it out at this point. I am also open to better solutions though please be aware I am very much a beginner on google appscript, nothing too complex please.
thankyou
In principle your script correctly adds a new sheet to the new spreadsheet before removing the preexisting one
However, mind that calls to service such as SpreadsheetApp are asynchronous.
And this becomes the more noticeable, the longer your script runs.
In your case it apparently leads to behavior that the only sheet is being deleted before the new sheet is being created.
To avoid this, you can force the execution to be synchronous by implementing calls to SpreadsheetApp.flush().
This will ensure that the old sheet won't be deleted before the new one gets inserted.
Sample:
copy.deleteSheet(copy.getSheets()[0]);// remove original "Sheet1"
SpreadsheetApp.flush();
copy.getSheets()[0].setName(name);
You might want to introduce call toflush()` also at other positions where it is important for the code to run synchronously.
OK, still rookie coder but getting better. Able to modify codes but not write most of them myself yet. Here is my current problem.
I run a small business and we use google sheets as our CRM (its faster and easier for us to do it this way) I have a master sheet that I bring in with =importrange everyone else jobs. It works perfect, makes my life real easy but there is one thing I can not get to come over. That is the notes stored in a cell. I have to actually open their sheet to view the notes. So I am trying to get a script that would update the notes down the importedrange. Then each day when I go over their info I push a button and it would write the notes from the other persons sheet onto my sheet, can just write over the last note and replace it.
I made an example with 3 sheets (all made editable for everyone) since I can't post our actual business sheets to work with. I should be able to modify it and transfer to my actual sheets after some help.
(Master Sheet) https://docs.google.com/spreadsheets/d/1TMNyohd5Vtn3p9cpLebmZASt2TzbWL80fIesCu89-ig/edit?usp=sharing
(Employee 1)
https://docs.google.com/spreadsheets/d/1n4iFXGuC7yG1XC-UIbuT9VrQ7rJWngPkDCv0vsvDed4/edit?usp=sharing
(Employee 2)
https://docs.google.com/spreadsheets/d/1EJVa5TgF6UkLhiLtfQ6o7BzpdzXDGcVhkibLCYwlfAU/edit?usp=sharing
Links are provided to each other sheet on the top of the master sheet. This is above my head so I won't try to butcher the code below lol. Here is a function I found but don't know how to implement it to use with import range.
function getNotes(rangeAddress) {
// returns notes inserted with Insert > Note from one cell or a range of cells
// usage:
// =getNotes("A1"; GoogleClock())
// =getNotes("A1:B5"; GoogleClock())
// see /docs/forum/AAAABuH1jm0xgeLRpFPzqc/discussion
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRangeByName(rangeAddress);
if (!range) return '#N/A: invalid range. Usage: =getNotes("A1:B5"; GoogleClock())';
var notesArray = new Array();
for (var i = 0; i < range.getHeight(); i++) {
notesArray[i] = new Array();
for (var j = 0; j < range.getWidth(); j++) {
notesArray[i][j] = range.getCell(i + 1, j + 1).getComment();
}
}
return notesArray;
}
So The code I would want it to read the note from "Employee 1" sheet and write it onto the "Master" sheet in the correct cell. Since it is an =importrange the orientation of the cells will always be the same on both sheets, just needs to pick the starting cell and go down the list. I want to make it work with the button I put on the top of the master sheet on each tab.
This script uses outdated methods. For example, GoogleClock() is gone.
Please see my other response to your similar question for a possible solution.
What I'd like to do is warehouse information from a particular sheet within a spreadsheet and copy it to a second spreadsheet at the end of every day. The second spreadsheet will run complex pivots and reports against the copied information that don't need to run throughout the day.
I can set up a time-driven trigger which will run the job every day within an hour block.
I'm working on the following script which uses SpreadsheetApp.getActiveSpreadsheet to get the current Spreadsheet. Then gets the individual sheet to backup with spreadsheet.getSheetByName. And then uses the sheet.copyTo method to add the current sheet to a new spreadsheet. I'm getting the new spreadsheet by looking up the id with SpreadsheetApp.openById all like this:
function startBackupJob() {
var currentSpreadSheet = SpreadsheetApp.getActiveSpreadsheet()
var masterSheet = currentSpreadSheet.getSheetByName("Sheet1")
var backupSpreadSheetId = "#######################################";
var backupSpreadSheet = SpreadsheetApp.openById(backupSpreadSheetId);
// var backupSheet = backupSpreadSheet.getSheetByName("Sheet1");
// backupSpreadSheet.deleteSheet(backupSheet);
masterSheet.copyTo(backupSpreadSheet).setName("Sheet1");
}
The issue I'm having is that copyTo will create a new worksheet rather than overwrite the existing spreadsheet. The point of moving to the new workbook is to run pivot tables off the data and not re-wire them to point to a new sheet.
I can delete the previous sheet to make room for the new one, but this kills the references on the PivotTable as well, so it doesn't help much.
Is there an easy way to transfer the entire contents of one worksheet to another?
This is similar to (but different from) the following questions:
How do I script making a backup copy of a spreadsheet to an archive folder? - However, I don't want to move the whole file, but a specific sheet within the spreadsheet.
How can copy specifics sheet to another spreadsheet using google script & copy one spreadsheet to another spreadsheet with formatting - However copying produces a new sheet, whereas I need to replace the contents of an existing sheet
Scripts, copy cell from one sheet to another sheet EVERYDAY at a specific time - However, I do want to replace the entire sheet, rather than just specific cells within the sheet.
Update
I might be able to do this by calling getRange on each sheet and then using getValues and setValues like this:
var currentValues = masterSheet.getRange(1, 1, 50, 50).getValues()
backupSheet.getRange(1, 1, 50, 50).setValues(currentValues)
But I'm worried about edge cases where the master sheet has a different available range than the backup sheet. I also don't want to hardcode in the range, but for it to encompass the entire sheet. If I call .getRange("A:E") then the two worksheets have to have the exact same number of rows which is not likely.
Your update has you about 90% of the way there. The trick is to explicitly check the size of the destination sheet before you copy data into it. For example, if I did something like this:
var cromulentDocument = SpreadsheetApp.getActiveSpreadsheet();
var masterSheet = cromulentDocument.getSheetByName('master');
var logSheet = cromulentDocument.getSheetByName('log');
var hugeData = masterSheet.getDataRange().getValues();
var rowsInHugeData = hugeData.length;
var colsInHugeData = hugeData[0].length;
/* cross fingers */
logSheet.getRange(1, 1, rowsInHugeData, colsInHugeData).setValues(hugeData);
...then my success would totally depend upon whether logSheet was at least as big as masterSheet. That's obvious, but what's less so is that if logSheet is bigger then there will be some old junk left over around the edges. Ungood.
Let's try something else. As before, we'll grab the master data, but we'll also resize logSheet. If we don't care about logSheet being too big we could probably just clear() the data in it, but let's be tidy.
var cromulentDocument = SpreadsheetApp.getActiveSpreadsheet();
var masterSheet = cromulentDocument.getSheetByName('master');
var logSheet = cromulentDocument.getSheetByName('log');
var hugeData = masterSheet.getDataRange().getValues();
var rowsInHugeData = hugeData.length;
var colsInHugeData = hugeData[0].length;
/* no finger crossing necessary */
var rowsInLogSheet = logSheet.getMaxRows();
var colsInLogSheet = logSheet.getMaxColumns();
/* adjust logSheet length, but only if we need to... */
if (rowsInLogSheet < rowsInHugeData) {
logSheet.insertRowsAfter(rowsInLogSheet, rowsInHugeData - rowsInLogSheet);
} else if (rowsInLogSheet > rowsInHugeData) {
logSheet.deleteRows(rowsInHugeData, rowsInLogSheet - rowsInHugeData);
}
/* likewise, adjust width */
if (colsInLogSheet < colsInHugeData) {
logSheet.insertColumnsAfter(colsInLogSheet, colsInHugeData - colsInLogSheet);
} else if (colsInLogSheet > colsInHugeData) {
logSheet.deleteColumns(colsInHugeData, colsInLogSheet - colsInHugeData);
}
/* barring typos, insert data with confidence */
logSheet.getRange(1, 1, rowsInHugeData, colsInHugeData).setValues(hugeData);
What's going on here is pretty straightforward. We figure out how big the log needs to be, and then adjust the destination sheet's size to match that data.
I have a Google Drive Spreadsheet in which I'm trying to have a formula autopopulate all the way down the rows, as users submit data via a webform attached to the spreadsheet. The tricky part is that I use a CONCATENATE function already, to perform a concatenation of the data submitted on several columns into one single cell.
However, for the CONCATENATE function to work, I have to "apply" it to newly submitted rows.
Is there a way to automate the filling of this formula down the rows in the spreadsheet?
I've tried to place an ArrayFormula function to it, even setting the range (A1:A), but I couldn't find the proper syntax for it work, if it may like this.
The function goes:
=CONCATENATE(CHAR(10)&X14&V14&Y14&J14&" "&K14&" "&L14&M14&N14&O14&" "&P14&" "&Q14&R14&S14&CHAR(10)&T14&"."&CHAR(10)&U14&"."&CHAR(10)&W14&CHAR(10)&CHAR(10)&CHAR(10)&I14&CHAR(10)&Z14&" "&AA14&CHAR(10)&AB14&AC14&AD14&AE14&AF14&AG14&AH14&"."&CHAR(10)&AI14&AJ14)
Any suggestion will be greatly appreciated.
(Answered by the OP in a question edit. Transformed into a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
I've found a little script from the Script Gallery of Google Spreadsheet (AutoFormulas, by tuxincarnate[#]gmail[dot]com), which solves the trick! Just tested it with a dozen of submissions from the webform and it does what it promises, autopopulate with formulas down the columns where applied.
// Updates all rows except the last to have the same formulas as row 3 (allowing for a header and different row 2 formula)
// To activate this functionality, the last row in the column should have the value '(auto)'
function UpdateFormulas() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetCount = ss.getNumSheets();
for (var sheetIndex = 0; sheetIndex < sheetCount; ++sheetIndex) {
var sheet = ss.getSheets()[sheetIndex];
var rowCount = sheet.getMaxRows();
var columnCount = sheet.getMaxColumns();
if (rowCount < 5) continue;
for (var columnIndex = 1; columnIndex <= columnCount; ++columnIndex) {
if (sheet.getRange(rowCount, columnIndex).getValue() == '(auto)') {
var row3Range = sheet.getRange(3, columnIndex);
for (var rowIndex = 4; rowIndex < rowCount; ++rowIndex) {
if (sheet.getRange(rowIndex, columnIndex).isBlank()) {
row3Range.copyTo(sheet.getRange(rowIndex, columnIndex));
}
}
}
}
}
}
#David Tew wrote:
Whilst you have a solution already, you might like to consider for the future the following formula, which is what you were originally looking for (You don't need to use CONCATENATE since you are choosing the columns to join together with & symbol)
=arrayformula(CHAR(10)&X2:X&V2:V&Y2:Y&J2:J&" "&K2:K&" "&L2:L&M2:M&N2:N&O2:O&" "&P2:P&" "&Q2:Q&R2:R&S2:S&CHAR(10)&T2:T&"."&CHAR(10)&U2:U&"."&CHAR(10)&W2:W&CHAR(10)&CHAR(10)&CHAR(10)&I2:I&CHAR(10)&Z2:Z&" "&AA2:AA&CHAR(10)&AB2:AB&AC2:AC&AD2:AD&AE2:AE&AF2:AF&AG2:AG&AH2:AH&"."&CHAR(10)&AI2:AI&AJ2:AJ)
this should go in the second row
The OP wrote:
#DavidTew showed me a clear and easy way to have it solved. The ArrayFormula should go alone, telling it to put together the ranges for every column into every single row. Works like charm. Proper syntax is: =arrayformula(A2:A&B2:B&C2:C), in order to have contents from cells A2, B2 and C2 "concatenated" into the cell where the ArrayFormula is applied. The most important issue is that by using this function, it autpopulates all the way down the rows as users submit data via a webform attached to the spreadsheet.