Adding Variables to getRange() - javascript

Having a hard time with the below Google Scripts JS code.
Here's what it's supposed to do.
Copy and paste info from active sheet from column M to column AA
Go to sheet 2, get the last cell with data and add one row before pasting the new information. If nothing is there then paste to the top of the sheet
Upon first paste there is no active cells yet as its a fresh sheet so the info should be pasted directly at the top
This line here is giving me the trouble, I want to put in my last_row variable into getRange. Some docs say you should be able to do something like spreadsheet.getRange("A:"last_row) but that isnt working for me. Here's the current line, spreadsheet.getRange("A1").activate();
function NEW() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('M1:AA12').activate();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet2'), true);
spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
var last_row = spreadsheet.getCurrentCell().getRowIndex();
spreadsheet.getRange("A1").activate();
spreadsheet.getRange('\'MAIN SHEET\'!M1:AA12').copyTo(spreadsheet.getActiveRange(),
spreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};
So essentially I am trying to paste data from one sheet to a second sheet. Upon paste I need the macro to find the last row with data in it from the previous paste and add one row so new data gets pasted below without any data overlapping.
Any ideas?

Regarding your 4th point:
This line here is giving me the trouble, I want to put in my last_row variable into getRange. Some docs say you should be able to do something like spreadsheet.getRange("A:"last_row) but that isn't working for me. Here's the current line, spreadsheet.getRange("A1").activate();
It's not working because the concatenation operator is missing:
spreadsheet.getRange("A:" + last_row)

Related

Google Sheets Scripts: Can you get a range from a rangeId?

My google sheet has a cell on sheet1 that contains a link to a cell on sheet2. In my function, I am able to get the link url, but cannot figure out how to get a range from the rangeId:
var link = generatorSheet.getRange(currRow, 2)
var linkUrl = link.getRichTextValue().getLinkUrl()
Logger.log(linkUrl) // linkUrl = "rangeid=1843553975"
I've tried using getRangeByName and various other functions but keep getting a null value back, not a Range object.
Thanks in advance!
Edit: My overall goal in this is to iterate over each row in sheet1, where each cell in column 2 links to a cell in sheet2. I need to take the value from the cell in sheet2 and copy it into sheet3. In sheet1, there's a check box in column 1 of each row, so that's what I'm using to determine whether or not the linked to value will be copied. I'll have a button to kick off my function and populate sheet3, and it has to assume these links are already in place - they were done by hand prior
When you create an hyperlink to a range using the user interface, you are facing this issue. I think you may have to change the way of designing the hyperlink and try to define it by the formula
=hyperlink("#gid=123456789&range=A2","go to ...")
and then you will retrieve the range by
Logger.log(linkUrl.match(/(?<=range=).*/g))
For documentation purposes,
This is a url hash fragment:
#rangeid=1843553975
The id seems to be created, when inserting a link to a range using the user interface. This is distinctly different from a namedRange When clicked, it's appended to the url in the browser, i.e.,https://docs.google.com/spreadsheets/id/edit#rangeid=1843553975. Once appended, through onpopstate javascript event, the range linked to the id is highlighted in the browser/app.
NamedRanges has a similar workflow. It also provides a rangeid=<10 digit ID>. But, it also has a name attached to it. But even in this case, the rangeid is not retrievable, though Sheets API provides a obfuscated range id.
There was a feature request made to Google, but it was made obsolete, because of lack of response on the part of the requestor:
https://issuetracker.google.com/issues/162810351
You may create a new similar issue there with a link to this answer. Once created, link the issue here.
Other related trackers:
https://issuetracker.google.com/issues/129841094
https://issuetracker.google.com/issues/134986436

How I get access to new intervals using "getNextDataRange()" of Selection Class?

I'm facing an error when I try to get values using the Method "getNextDataRange(Direction)" but I can't understand where I missed out.
first: I Opened another spreadsheet and selected the first sheet. I SET "B2" as initial current cell. Then I back to select the actual sheet to get access of "Selection" Class, so finally I can use "getNextDataRange":
Heres my code:
function ok() {
var sheets = SpreadsheetApp.openById("SHEET ID").getSheets()
var firstsheet = sheets[0].getRange("B2").activateAsCurrentCell().getSheet().getSelection().getNextDataRange(SpreadsheetApp.Direction.RIGHT).getValues
return SpreadsheetApp.getActiveSpreadsheet().getRange("B1").activate().setValue(firstsheet[0][0])
}
--
3. Then I wanna bring the values obtained in the range select by the getNextDataRange to import to my actual spreadsheet. Start from the range "B1" and taking the first line and the first column of the selection that I got previously.
The fallow error occours:
Cannot find getNextDataRange ((class)) method.
Someone has already faced that? I appreciate if someone could explain what detail I missed. I believe that is that doubt of many other too.

How do you copy more than 1000 rows to a new Google Sheet?

I have some code that pulls a range of data from a source sheet in another file and copies it to a new sheet in the current file. It used to work but now that the source range is over 1000 rows, the copy fails entirely and without error (the copy doesn't occur and the code moves along). It seems as though it's because my destination sheet only has 1000 rows and trying to copy something larger than that causes it to fail.
The "Execution Transcript" doesn't give me any insight as to why it fails. As a test, I shortened the source data to less than 1000 rows and it worked again.
The chunk of my code that copies the range is this:
// COPY DATA FROM SOURCE SPREADSHEET TO TEMP SHEET IN ACTIVE SPREADSHEET
var SRange = source_s.getDataRange();
var A1Range = SRange.getA1Notation();
var SData = SRange.getValues();
temp_s.getRange(A1Range).setValues(SData);
temp_s is the destination sheet.
source_s is the source sheet.
I suppose either of two solutions could work so I could get more than 1000 rows copied to my destination sheet:
Use a type of copy function that will automatically resize the sheet to handle the size of the range, or
Find a way to extend the sheet's size prior to the copy, similar to the "Add 1000 more rows at bottom" function you normally see at the bottom of a google sheet.
I posted this as a comment, but it should probably go as an answer too.
I had declared the range on the destination sheet to be simply "A:J" which would select all the rows for those two columns. That in effect made it A1:J1000. That works if your source is less than 1000 rows, but once the source is bigger than the desination, it fails.
TO SOLVE IT I found the last row of the source data using lastrow = source_s.getLastRow() and then named my destination range as "A1:+J"+lastrow. The copy worked.

Google Script: function that insert new row copying functions/formulas from last row

I have a table which cells have functions/formulas, like this one:
I need a script that create a new row copying to it the functions/formulas of the last used row.
I find this script which create a new row but it doesn't copy functions/formulas. How could I implement this formatting copy task in Google Script without having to manually select and copy?
Thanks for any help!
You can copy formulas just as easily you copy values, just use Range.getFormula() and Range.setFormula() instead of .getValue() and .setValue(). See documentation on spreadsheet service.
Inserting a row below the last one is pretty basic, use insertRowAfter and getLastRow in a simple script.
EDIT : in case you don't find it, here is an example of another simple way to do it, copying everything in one step
function duplicateLastRow(){
var ss = SpreadsheetApp.getActiveSheet();
ss.insertRowAfter(ss.getLastRow());
ss.getRange(ss.getLastRow(),1,1,ss.getLastColumn()).copyTo(ss.getRange(ss.getLastRow()+1,1));
}
Method Sheet.appendRow allow append row in one command as atomic action.

prevent cells in being edited in google spreadsheet - google docs script

I've got a master sheet that I need to view and filter data from. The data is brought into the sheet using the =Sheet2!B7 syntax.
The problem is that I keep accidentally editing the data in the master sheet which does not update the original copy.
I would like a script that alerts me if I'm in the master sheet and stops me from editing the cells. I still want to be able to filter the data so simply locking the sheet would work.
I've been trying to modify this script (posted by Yuzhy) but so far I haven't been able to get it to work.
(I'm not sure whether this is the right place for this question, it was either this or stackexchange / superuser, if it's wrong please advise.)
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var CellRow = SpreadsheetApp.getActiveRange().getRow();
var CellColumn = SpreadsheetApp.getActiveRange().getColumn();
if (CellColumn == 2){
sheet.getRange(CellRow, CellColumn).setFormula("=A"+CellRow+"+1");
Browser.msgBox("DON'T MESS WITH THE FORMULAS!");
}
}
Any help much appreciated.
From reading your code it seems that you're trying to do a different thing from what you've explained. I see that you trying to "repair" the formulas. But why if (CellColumn == 2 )? You want to protect only column B, not the whole "master" sheet?
Can you share a sample spreadsheet of what your sheet structure looks like?
Anyway, I'll suppose that you want to warn when you overwrite anything on your "master" sheet, auto-repairing the formula is a little more complicated (depending on your scenario), and after reading the popup it's easy to just hit undo and recover it. But you really mean to auto-repair the formulas, I'll enhance my code after you share a sample of your spreadsheet, since it's a slightly complicated and depends highly on your structure.
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Master" )
Browser.msgBox("DON'T MESS WITH THE FORMULAS!");
}
If you're doing simple reference formulas on other sheets it's somewhat easier and probably a good solution for you to use an ArrayFormula, that will auto-replace back the value when you change any cell, except for the first cell, but then a manual undo will be so rare and obvious that it will not be an issue, I think. I did an example of array formula on the spreadsheet you linked, please take a look. On A1 I wrote:
=ArrayFormula(Sheet1!A1:F20)
Now, if you go and accidentally writes something on B2 for example, it value will automatically come back. Try and see if that's a good solution for you.
Update - as of 8/8/12 google has updated its spreadsheets and now allows you to have "protected ranges" - https://support.google.com/docs/bin/answer.py?hl=en&answer=63175

Categories