Copying data from spreadsheet to another and to an active cell - google-apps-script

Hope you guys are able to help me. I have been googling my eyes off...
I'm trying to copy data from one cell (B2) to another spreadsheet (the spreadsheet in use of course). I get the data, but it goes to cell A1 every time.
The cell that I copy the data to will be moving right every week, that is why I can't use a fixed cell.
Here is the code:
function a(){
var test = SpreadsheetApp.openById("mysourcespreadsheet").
getSheetByName("mysourcesheet").getRange("B2").getValues();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getCurrentCell();
cell.setValue(test);
}
The thing I really wanted to do is to copy the variable 'test' to the first empty cell in row 4, but let's just take on step at the time as I'm fairly new to the google scripts :)

Aaaargh... My stupidity hurts so much! I think I found the error. var sheet = ss.getSheets()[0]; -> should be var sheet = ss.getActiveSheet();
Thanks for the help thou

Related

Google sheet script to add a row above a specific cell once that has been filtered out

I've been trying to build a spreadsheet where a button, once it's been clicked, it would build a new row above a specific cell containing a fixed value/sting.
Practical example would be a sheet containing cells with different values and the script should run through all the cells, find a cell with a specific string and add an empty row above that.
I've been looking around for a similar script to tweak and adapt to my situation but all of my attempts have been unsuccessful so far.
This is what I've got:
function AddRowAbove() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //get the active spreadsheet
var sheet = ss.getActiveSheet(); // get the active sheet
var rangeData = sheet.getDataRange(); //get all the data in the spreadsheet (is that the right way to do this??
// for every data within the range of data variable
for (var i = 0; i< rangeData.length ; i++){
if(rangeData[i] == "TOT") // Check to see if cell has "TOT" as value
{
ss.insertRowsBefore(spreadsheet.getActiveRange().getCell(rawData[i]), 1); // is that the right function to call???
}
}
Though logically this seems to be correct, I'm not used to script with this programming language so it's hard for me to find where the problem is.
Any help would be greatly appreciated.
Also, can anyone point me out to any resource I can study to get the basic of this scripting language??
Thanks!

Google Sheets Macro not completing

I'm trying to parse a CSV file using Google Sheets macros. I've recorded all the steps as individual macros, and one by one they work fine, but when I combine into one macro, it doesn't run properly. The point at which it stops working is after the PODdateformatting part has completed and it's run through the first three lines of Daystodeliverformula. Cell H2 is populated with the formula, but the formula doesn't then autofill down the rest of the column. Any ideas? Or indeed, am I going about this all wrong and need a good talking to? :-)
function TheWholeShebang() {
var spreadsheet = SpreadsheetApp.getActive(); // start of DeletedUnwantedColumns
spreadsheet.getRange('AA:DE').activate();
spreadsheet.getActiveSheet().deleteColumns(spreadsheet.getActiveRange().getColumn(), spreadsheet.getActiveRange().getNumColumns());
spreadsheet.getRange('W:X').activate();
spreadsheet.getActiveSheet().deleteColumns(spreadsheet.getActiveRange().getColumn(), spreadsheet.getActiveRange().getNumColumns());
spreadsheet.getRange('R:U').activate();
spreadsheet.getActiveSheet().deleteColumns(spreadsheet.getActiveRange().getColumn(), spreadsheet.getActiveRange().getNumColumns());
spreadsheet.getRange('H:P').activate();
spreadsheet.setCurrentCell(spreadsheet.getRange('P1'));
spreadsheet.getActiveSheet().deleteColumns(spreadsheet.getActiveRange().getColumn(), spreadsheet.getActiveRange().getNumColumns());
spreadsheet.getRange('A:E').activate();
spreadsheet.setCurrentCell(spreadsheet.getRange('E1'));
spreadsheet.getActiveSheet().deleteColumns(spreadsheet.getActiveRange().getColumn(), spreadsheet.getActiveRange().getNumColumns()); // end of DeletedUnwantedColumns
var spreadsheet = SpreadsheetApp.getActive(); // start of Addcolumnsandheaderlabels
spreadsheet.getRange('A:F').activate();
spreadsheet.getActiveSheet().insertColumnsAfter(spreadsheet.getActiveRange().getLastColumn(), 6);
spreadsheet.getActiveRange().offset(0, spreadsheet.getActiveRange().getNumColumns(), spreadsheet.getActiveRange().getNumRows(), 6).activate();
spreadsheet.getRange('G1').activate();
spreadsheet.getCurrentCell().setValue('POD Date (formatted)');
spreadsheet.getRange('H1').activate();
spreadsheet.getCurrentCell().setValue('Days to Deliver');
spreadsheet.getRange('G2').activate(); // end of Addcolumnsandheaderlabels
var spreadsheet = SpreadsheetApp.getActive(); // start of PODdateformatting
spreadsheet.getRange('G2').activate()
.setFormula('=DATE(LEFT(D2,4),mid(D2,5,2),right(D2,2))');
spreadsheet.getActiveRange().autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES); // end of PODdateformatting
var spreadsheet = SpreadsheetApp.getActive(); //start of Daystodeliverformula
spreadsheet.getRange('H2').activate()
.setFormula('=NETWORKDAYS(E2,G2,Instructions!$B$15:$B$40)-1');
spreadsheet.getActiveRange().autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES); // end of Daystodeliverformula
};
After messing about with range.autoFillToNeighbor() and failing (see comments above) I was still suspicious about that method.
When I used this the range.autoFill() method instead it all worked fine. See code below.
// start of PODdateformatting
//var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('G2').activate().setFormula('=DATE(LEFT(D2,4),mid(D2,5,2),right(D2,2))');
var sourceRange = spreadsheet.getRange("G2:G2");
var destination = spreadsheet.getRange("G2:G369");
sourceRange.autoFill(destination,SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
//start of Daystodeliverformula
var spreadsheet = SpreadsheetApp.getActive();
var range = spreadsheet.getRange('H2').activate().setFormula('=NETWORKDAYS(E2,G2,Instructions!$B$15:$B$40)-1');
var sourceRange = spreadsheet.getRange("H2:H2");
var destination = spreadsheet.getRange("H2:H369");
sourceRange.autoFill(destination,SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
In hindsight I now believe that range.autoFillToNeighbor() was never right for your use case in the first place!
range.autoFillToNeighbor() expects to build autofill formulas based on data that is contained in neighbouring columns. It tries to do this intelligently, but neighbouring columns do not contain anything useful! Its amazing it ever worked... maybe sometimes defaulting to range.autoFill()!
range.autoFill() on the other hand, just duplicates the formula (data) above or below ( NOT looking to neighbouring cells for help).
You can copy and paste these over the corresponding functions in function TheWholeShebang() and should all work.
Note I assume a fixed range of 369 as per your data, but you can calculate this based on actual size if you prefer, in case no of rows is changed.

Copy Google sheet to a new sheet using cell value from 3rd sheet

I've been looking through the forums trying to search for the right way to do this but I can't seem to get it right. This is my first time using Google Apps Script so I'm learning as I'm going.
This is what I'm trying to do.
1) I want to duplicate all the contents of an old sheet into a new sheet. The script will determine the existing sheet name by referring to the cell b17 from 'Statistics' sheet, and will duplicate the old sheet, including values formats, references and formulas. The duplicated sheet will be named from cell c17 of the 'Statistics' sheet.
2) If possible I would also like to make the old sheet remove all the references and just keep the values and formats after the new sheet has been created. Similar to the copy all and ctrl-shift-v, except automating it in one fell swoop.
This is the code i currently have, not sure if it is correct
function newSheetLast() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("Statistics").activate();
var oldSheetName = ss.getRange('b17').getDisplayValue();
var newSheetName = ss.getRange('c17').getDisplayValue();
var sheet = ss.getSheetByName(oldSheetName).activate();
var source = SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet(newSheetName);
};
I am getting stuck when trying to do 1. I tried the copyTo and can get the sheet to copy, but loose all the formatting and formulas when i copy over to the new sheet.
I am not sure how to even attempt 2
You variable naming and the way duplicating sheets works is a bit confusing.
You should really be able to duplicate a Sheet Object directly or at least be able to try and supply the name of the sheet you are trying to duplicate but no, it is on a Spreadsheet level and only works on the active sheet...
Duplicating a sheet carries formulae and formatting.
Overwriting with static values can be done with setValues(getValues).
function newSheetLast() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var settings = ss.getSheetByName("Sheet1");
var oldSheetName = settings.getRange('B17').getDisplayValue();
var oldSheet = ss.getSheetByName(oldSheetName);
var newSheetName = settings.getRange('C17').getDisplayValue();
ss
.getSheetByName(oldSheetName)
.activate()
.getParent()
.duplicateActiveSheet()
.setName(newSheetName);
oldSheet.getDataRange().setValues(oldSheet.getDataRange().getValues());
};

google apps script - paste in next empty row

with google apps script I am collecting data from the google analytics API.
This is set to collect data every night 1 am for the previous day and writing that in to a sheet “original”
In my second script I want to copy a range A1:G1 from the sheet “original” to my second sheet “copy”
And what I want is continuously to copy the data to the next empty row, but how?
So far I have this as a basic solution, but this is always pasting the selected data into the defined cell (in this case cell A10)
function copytestdata() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("original");
var sheet2 = ss.getSheetByName("copy");
sheet1.getRange("A1:G1").copyTo(sheet2.getRange("A10"), {contentsOnly:true});
}
I would like a dynamic solution on the second sheet “copy”.
So new data should be pasted in to the next empty row starting from cell A1 and the go down to next empty row.
But how do I get the script to go down to the next empty row?
sheet1.getRange("A1:G1").copyTo(sheet2.[DYNAMIC SOLUTION]), {contentsOnly:true});
Have anyone got a brilliant idea? I would really appreciate the help.
Ohh and by the way how can I actually go to a specific cell sort of like:
sheet1.getActiveRange(“B8”)
Thanks a lot in advance for your help
Pelikan76
why not using getLastRow()+1 ?
function copytestdata() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName("original");
var sheet2 = ss.getSheetByName("copy");
sheet1.getRange("A1:G1").copyTo(sheet2.getRange(sheet2.getLastRow()+1,1,1,7), {contentsOnly:true});
}

Writing variables to the next available spreadsheet row in a Google Apps Script

Quick question: I am a newbie to Google Apps Script, and want to do something really simple. I have a spreadsheet where I would like to log my results every time the script runs. Let's say I have three variables, and each time I execute, I want to go to the first available empty row in the sheet, and assign variable #1 to Column A, variable #2 to Column B, etc. I'm guessing there's all types of examples where that kind of thing happens every day. Can someone point me to such an example?
Thanks for your help.
TomC
maybe this way is better or at least shorter:
var logSheet = SpreadsheetApp.openById(logSpreadsheetId).getSheets()[0];
logSheet.appendRow([var1, var2, var3]);
In your Google Apps Script, you will want to look at something called sheet.getLastRow()
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// This logs the value in the very last cell of this sheet
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var lastCell = sheet.getRange(lastRow, lastColumn);
Logger.log(lastCell.getValue());
Source: https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow()