getsheetbyname with variable cell - google-apps-script

I have a sheet called Audit with cell B1 corresponding to a specific shopID.
I have built a sheet with each shopID called ShopID+PrevAudit (555PrevAudit)
When they complete the audit they click a button that should copy values and format to the corresponding sheet i've created but I'm getting hung up on calling the correct sheet based on a B1 entry.
This is what I had been using but it was static and i want to make this easier on myself. I'm not sure why this is so difficult for me. Thanks for any help you can provide.
function copyaudit() {
var source = SpreadsheetApp.openById('SheetID');
var sourceSheet = source.getSheetByName('Audit');
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var tempSheet = source.getSheetByName('555PrevAudit');
var tempRange = tempSheet.getRange('A1:L51');
var destination = SpreadsheetApp.openById('SheetID');
sourceRange.copyTo(tempRange); // paste all formats?, broken references
tempRange.offset(0, 0, sourceValues.length, sourceValues[0].length)
.setValues(sourceValues); // paste all values (over broken refs)
}

Using a JS template string, you can generate the sheet name:
`${destID}PrevAudit`
To put it in context:
function copyaudit()
{
const range = 'A1:L51';
let spreadSheet = SpreadsheetApp.openById('SheetID');
let sourceSheet = spreadSheet.getSheetByName('Audit');
let sourceRange = sourceSheet.getRange(range);
// Get B1
let destID = sourceRange.getValues()[0][1];
let destSheet = spreadSheet.getSheetByName(`${destID}PrevAudit`);
sourceRange.copyTo(destSheet.getRange(range));
}

Related

Google App Script - how to Copy Paste values ( only non empty cells) of a data range with , from a Spreadsheet to another Spreadsheet

Objective - To copy all non-empty cells from a Spreadsheet-1 to Spreadsheet-2.
I saw some codes online and modified for my use, sharing below.
I need help in getting the script right so that a variable range(i.e. to selects non-empty up to last rows and last columns) can be selected and data copied to Spreadsheet-2.
I am trying to make it workable for 'A1:GZ1000' range.
If numbers of rows / cols with non-zero (non-empty) increases, script needs to update range for passing values to Spreadsheet-2.
''''
function dataImport(ssaID, ssbID) {
// source doc
var ssaID = '1DZX1Jb4qwCHETtAENIsRioJvl4TC0hUWZDn_k1q3oes' ;
var sheet = SpreadsheetApp.openById(ssaID);
var ssbID = '1HptKwYzdWCsz9oey9hOouhWNTQ3GAyu9oswZ1xgP3D0' ;
// source sheet
var ss = sheet.getSheetByName('Data - Price');
// Get full range of data
var SRange = ss.getDataRange();
// get A1 notation identifying the range
var A1Range = SRange.getA1Notation();
// get the data values in range
var SData = SRange.getValues();
// Logger.log(SData)
// target spreadsheet
var tss = SpreadsheetApp.openById(ssbID);
// target sheet
var ts = tss.getSheetByName('Data - Price');
// Clear the Google Sheet before copy
ts.clear({ contentsOnly: true });
Logger.log(SRange.length);
// set the target range to the values of the source data
var tsRange = ts.getRange(1,1,SRange.length,SRange[0].length);
tsRange.setValues(Sdata);
}
''''
Pl. do ask for details if you require.
R U
Try it this way:
function dataImport(ssaID, ssbID) {
var ssaID = '1DZX1Jb4qwCHETtAENIsRioJvl4TC0hUWZDn_k1q3oes';
var ss = SpreadsheetApp.openById(ssaID);
var ssbID = '1HptKwYzdWCsz9oey9hOouhWNTQ3GAyu9oswZ1xgP3D0';
var sh = ss.getSheetByName('Data - Price');
var rg = sh.getDataRange();
var vs = rg.getValues();
var tss = SpreadsheetApp.openById(ssbID);
var tsh = tss.getSheetByName('Data - Price');
tsh.clearContents();
tsh.getRange(1, 1, vs.length, vs[0].length).setValues(vs);
}

How do i paste into another file through app script

I am using this code:
function copyInfo() {  
var ss = SpreadsheetApp.getActiveSpreadsheet();  
var copySheet = ss.getSheetByName("Product-analyse");  
var pasteSheet = ss.getSheetByName("Blad18"); // get source range  
var source = copySheet.getRange(93,7,39,6);  // get destination range  
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,39,6); // copy values to destination range  
source.copyTo(destination);  // clear source values
source.clearContent();
} 
Now its pasting in "Blad18". Instead I want it to be pasted in another file.
I tried adding {contentOnly: TRUE}. Though this didnt seem to work
I cannot figure this out unfortunately. Everything else is correctly set already.
Any help is greatly appreciated.
Updated script I am using:
function copyInfo() {
var ssSource = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ssSource.getSheetByName("Product-analyse");
var ssPaste = SpreadsheetApp.openById("1qhnA8L3ZkU-iEyOJtszAC4OW58sg2TJZSa_rmN_EXBI"); // the id of the other spreadsheet
var pasteSheet = ssPaste.getSheetByName("Submitted Data"); // get source range
var source = copySheet.getRange(93,7,39,6); // get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,39,6); // copy values to destination range
source.copyTo(destination); // clear source values
source.clearContent();
}
Try this:
function copyInfo() {
var ss = SpreadsheetApp.getActive();
var csh = ss.getSheetByName("Sheet0");
var psh = ss.getSheetByName("Sheet1");
const cshsr = 2;
var crg = csh.getRange(cshsr, 1, csh.getLastRow() - cshsr + 1, csh.getLastColumn());
var prg = psh.getRange(psh.getLastRow() + 1, 1);
crg.copyTo(prg);
}
I believe what you want to do is copy from one spreadsheet file to another spreadsheet file. Here is an example
function copyInfo() {
var ssSource = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ssSource.getSheetByName("Product-analyse");
var ssPaste = SpreadsheetApp.openById("dfsfhsfhskfhaskjfhsjkfas"); // the id of the other spreadsheet
var pasteSheet = ssPaste.getSheetByName("Blad18"); // get source range
var source = copySheet.getRange(93,7,39,6); // get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,39,6); // copy values to destination range
source.copyTo(destination); // clear source values
source.clearContent();
}
Reference
SpreadsheetApp.openById()

Copy dynamic range from one sheet to another

I am using the below code to copy my data from sheet1 to sheet2 and append the data in sheet2 if script runs again? The issue is that my range is not fixed in sheet 1,I want to copy whatever range contains the content should be copied to sheet2 Can anyone guide that what to change in the below code to get the result?
function copyInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copySheet = ss.getSheetByName("sheet1");
var pasteSheet = ss.getSheetByName("sheet2");
var source = copySheet.getrange(2,1,200,7);
var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,1,200,7);
source.copyTo(destination, {contentsOnly:true});
var data = copySheet.getRange(2,1,200,6)
data.clearContent()
}
Method1:
Include:
var paste_lr = pasteSheet.getLastRow()
Modify:
var source = copySheet.getrange(paste_lr+1,1,200,7);
Similarly change 200 using same function.
Method2:
var sp = PropertiesService.getScriptProperties();
var SourceLr = sp.getProperty("Source_Data_Rows") || 0;
var source = copySheet.getrange(SourceLr+1,1,200,7);
var Source_Lr = copySheet.getLastRow();
sp.setProperty("Source_Data_Rows", Source_Lr);

Google script for google sheets - Range copy paste special 'add'

i'm really newbie at scripting, i used to do my work with microsoft office that have a special paste "add" feature and now for google sheet i can't really find it.
I will have a source range of C2:C102 and destination at same sheet D2:D102 i want the script (that i can run manually weekly) to copy all the range from source and sum it with the already existing data at D2:D102 (only values).
Here is a small example - Before after
I tried to use this code but ofc it just replaces the values.
function copyCells(){
var thisSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var SourceSheet = thisSpreadsheet.getSheetByName("test");
var SourceRange = thisSpreadsheet.getRange("C2:C102");
var destinationSheet = thisSpreadsheet.getSheetByName("test");
var destinationRange = destinationSheet.getRange("D2:D102");
SourceRange.copyTo(destinationRange, {contentsOnly: true});
}
Any help will be really appreciated :)
Haven't tested the code but try this.
grab values with getValues()
sum the values
copy back values with setValues()
function copyCells(){
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const SourceSheet = spreadsheet.getSheetByName("test");
const SourceRange = spreadsheet.getRange("C2:C102");
const SourceValues = SourceRange.getValues();
const destinationSheet = spreadsheet.getSheetByName("test");
const destinationRange = destinationSheet.getRange("D2:D102");
const destinationValues = destinationRange.getValues();
for (let i = 0; i < SourceValues.length; i++)
destinationValues[i][0] = parseFloat(destinationValues[i][0]) + parseFloat(SourceValues[i][0])
destinationRange.setValues(destinationValues);
}
REFERENCES
range.getValues()
range.setValues()

Copy value and format from a sheet to a new google Spreadsheet document?

I need to copy a sheet on google SpreadSheet to another SpreadSheet document.
I´ve done my research, and I found two methods that do this, however both have problems that I don´t know how to fix.
The first method copies the sheet with format, but it keeps the referenced cells, so I get a reference error in the new document (#ref). I need a function that copies the format and the values (not references).
function copySheet() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var destination = SpreadsheetApp.openById("15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ");
sheet.copyTo(destination);
}
This second method copies the values without references, however it copies only values, without format.
function copySheetValues()
{
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sourceDataRange = source.getDataRange();
var sourceSheetValues = sourceDataRange.getValues();
var sourceRows = sourceDataRange.getNumRows();
var sourceColumns = sourceDataRange.getNumColumns();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
destination.insertSheet(sourcename, 0);
destination.getDataRange().offset(0, 0, sourceRows, sourceColumns).setValues(sourceSheetValues);
}
How do I write a function that keeps the format and copies the values?
Since you seem to know how to get and set values using the whole data range, just use the other methods to get and set all the other parameters.
The script editor autocomplete is a great help in this case to try not to forget one !
I hope the list is complete, it is a bit of a pain to write though !.
code below, if one of them is not useful to you just delete it (in both directions (set and get).
function copySheetValues(){
var source = SpreadsheetApp.getActiveSheet();
var sourcename = source.getSheetName();
var sValues = source.getDataRange().getValues();
var sBG = source.getDataRange().getBackgrounds();
var sFC = source.getDataRange().getFontColors();
var sFF = source.getDataRange().getFontFamilies();
var sFL = source.getDataRange().getFontLines();
var sFFa = source.getDataRange().getFontFamilies();
var sFSz = source.getDataRange().getFontSizes();
var sFSt = source.getDataRange().getFontStyles();
var sFW = source.getDataRange().getFontWeights();
var sHA = source.getDataRange().getHorizontalAlignments();
var sVA = source.getDataRange().getVerticalAlignments();
var sNF = source.getDataRange().getNumberFormats();
var sWR = source.getDataRange().getWraps();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
var destinationSheet = destination.insertSheet(sourcename, 0);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues)
.setBackgrounds(sBG)
.setFontColors(sFC)
.setFontFamilies(sFF)
.setFontLines(sFL)
.setFontFamilies(sFFa)
.setFontSizes(sFSz)
.setFontStyles(sFSt)
.setFontWeights(sFW)
.setHorizontalAlignments(sHA)
.setVerticalAlignments(sVA)
.setNumberFormats(sNF)
.setWraps(sWR);
}
Edit :
Bryan's answer and your comment made me think of another solution, much more simple and that handles merged cells as well. Here is the code :
function copySheetValuesV2(){
var source = SpreadsheetApp.getActiveSheet();
var sourceName = source.getSheetName();
var sValues = source.getDataRange().getValues();
var destination = SpreadsheetApp.openById('15ucPbZrIYXZAOCYVdpK6OA0oyQT1NcsmuiJmDRfdpHQ');
source.copyTo(destination)
var destinationSheet = destination.getSheetByName('Copy of '+sourceName)
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);// overwrite all formulas that the copyTo preserved
}
In both script be sure that the destination sheet name does not already exist. I didn't handle that case although it is quite easy to do with a try/catch structure.
Another route to try that I think Serge was alluding to here.
function myFunction() {
var source = SpreadsheetApp.openById('SOURCE_ID');
var sourceSheet = source.getSheetByName('Sheet1');
var sourceRange = sourceSheet.getDataRange();
var sourceValues = sourceRange.getValues();
var tempSheet = source.getSheetByName('temp');
var tempRange = tempSheet.getRange('A1');
var destination = SpreadsheetApp.openById('DEST_ID');
sourceRange.copyTo(tempRange); // paste all formats?, broken references
tempRange.offset(0, 0, sourceValues.length, sourceValues[0].length)
.setValues(sourceValues); // paste all values (over broken refs)
tempSheet.copyTo(destination); // now copy temp sheet to another ss
}
This is a variation upon Sergei's answer.
This script will copy all visible sheets and export them in to a new spreadsheet with " Final" appended to the document title.
function copySheetValuesV4(){
var sourceSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheets = sourceSpreadsheet.getSheets();
var destination = SpreadsheetApp.create(sourceSpreadsheet.getName()+' Final');
for (var i = 0; i < sourceSheets.length; i++){
var sourceSheet = sourceSheets[i];
if (!sourceSheet.isSheetHidden()) {
var sourceSheetName = sourceSheet.getSheetName();
var sValues = sourceSheet.getDataRange().getValues();
sourceSheet.copyTo(destination)
var destinationSheet = destination.getSheetByName('Copy of '+sourceSheetName).setName(sourceSheetName);
destinationSheet.getRange(1,1,sValues.length,sValues[0].length).setValues(sValues);// overwrite all formulas that the copyTo preserved */
}
destination.getSheetByName("sheet1").hideSheet() // Remove the default "sheet1" */
}
}