My numeric sheet name not found Range when use pure get Range - google-apps-script

I also have sheet name ..."4"... as a number
But it shows error as "Exception: Range not found"
I think because my sheet name is a number, but I really need the sheet name as a number
I try this, it should work. but it turns out, it's not
var ss = SpreadsheetApp.getActiveSpreadsheet()
var shname = ss.getRange("Home!A1") // A1 contains value 4 as a number
ss.getRange("'" + shname + "'!A1").setValue("is it worked?") // how to fix this line?
for fully info
https://docs.google.com/spreadsheets/d/1GcyfutUP-vg23H9mpjfNLRQvTkOqp0c8dN-J4R8g9Hk/edit#gid=1502470412&range=A1

You need to get the value of the range/cell. Change the second line in the script to
var shname = ss.getRange("Home!A1").getDisplayValue() //getValue() should also work
and see if that works?

Related

Replace text with hyperlinked version onEdit

I have a google sheet with a list of people's initials in range A4:A.
These initials are each hyperlinked to a different part of my sheet.
Column MM contains many cells that all have a data validation dropdown list referencing the initials list in A4:A
I need a script that triggers on edit so that when a user selects initials in the dropdown list in column MM, the script replaces it with the hyperlinked version from column A
My scripting knowledge is rudimentary. Normally I'd do a replace something like the below but I'm not sure how to implement the search so it takes the value from column MM and searches for it in columnA (or even if this would take the hyperlink function along with it.
`function replaceText(){
var oldText = "AB";
var newText = "AB hyperlinked";
var sheet = SpreadsheetApp.getActive().getSheetByName('SHOTS');
sheet.getRange("MM1:MM" + sheet.getLastRow()).createTextFinder(oldText).replaceAllWith(newText);
}`
Thanks in advance for any help given
If you have the chance of having an additional column, you can do a workaround without script with FILTER:
=FILTER(A2:A,A2:A=MM1)
Or if you want it as an array for many rows
=BYROW (MM1:MM,LAMBDA(each,IF(each="","",FILTER(A2:A,A2:A=each))))
Check in this image how when I chose value "b" it returns the hyperlinked value in the coloured column
OPTION B with SCRIPT:
Please check if MM is column 351, if not change that number. Run it once from the console (it will give an error, but it's just for approving the permissions), then go to your sheet and start trying with your dropdown:
function onEdit(e) {
var ecolumn = e.range.getColumn()
if (ecolumn == 351){
var sheet = SpreadsheetApp.getActive()
var range = sheet.getActiveRange();
var value = range.getValue()
var lookuprange = sheet.getRange("A:A").getValues().map(n => n[0])
var index = lookuprange.indexOf(value)+1
if (index != 0){
var link = sheet.getRange("A"+index).getRichTextValue().getLinkUrl()
var richValue = SpreadsheetApp.newRichTextValue()
.setText(value)
.setLinkUrl(link)
.build();
range.setRichTextValue(richValue);}}
}
REFERENCE: Apps Script: how to get hyperlink from a cell where there is no formula

How can I conditionally copy between Google sheets?

I would like to conditional copy a value from one sheet to another.
About the below script:
It checks if in SOURCE tab the value in column H is equal to 45 and if Column A is empty. If so, it should copy the value in Column G into the last row of column A in TARGET tab. It also ads data to some of the TARGET tab columns
If I change this: sourceSheet.getRange(rangeToCopy).copyTo(destination.getRange(destination.getLastRow()+1, 1)),{contentsOnly:true};
to this: sourceSheet.getRange(rangeToCopy).copyTo(destination.getRange(destination.getLastRow()-1, 1)),{contentsOnly:true}; the cell is pasted on Column A on the penultimate row, which makes me think that the present code tries to copy to a row after the last visible one instead of pasting into the next blank cell after a non blank one in Column A, hence returning the error explained on the next bullet
As is, it returns the error: The coordinates of the range are outside the dimensions of the sheet. (I understood that the problem is because of the use of getlasrow and being used as is, it's trying to retrieve a row that does not exist)
This is the code so far:
function CopyTo(){
var sheet = SpreadsheetApp.getActive();
var sourceSheet = sheet.getSheetByName("SOURCE");
var destination = sheet.getSheetByName("TARGET");
var lastRow = sourceSheet.getDataRange().getLastRow();
for(var row=3; row<=lastRow; row++){
if(sourceSheet.getRange(row,1).getValue() == "" & sourceSheet.getRange(row,8).getValue() >= "45"){
Logger.log("CELL H"+row+" has \">=45\""+"\n=================\n"+"CELL A"+row+" is \"empty\""+"\n=================\n"+"RANGE TO COPY:\n"+ "\"G"+row+":G"+row+"\"");
var rangeToCopy = "G"+row+":G"+row;
sourceSheet.getRange(rangeToCopy).copyTo(destination.getRange(destination.getLastRow()+1, 1)),{contentsOnly:true};
destination.getRange(destination.getLastRow(), 9).setValue("Added Text Column 9");
destination.getRange(destination.getLastRow(), 13).setValue("Added Text Column 13");
destination.getRange(destination.getLastRow(), 14).setValue(new Date());
}
}
}
Also, there are other columns in Target sheet that fetch values so maybe that's the reason why the script isn't pasting on the right place but I can't get it to work.
Could you be so kind to help out?
Thank you in advance.
This is a test sheet which returns the previously mentioned error when running the script.
UPDATE
I've added to the script:
var column = destination.getRange('A' + destination.getMaxRows())
var lastFilledRow = column.getNextDataCell(SpreadsheetApp.Direction.UP).getA1Notation().slice(1)
Logger.log(lastFilledRow);
so I would get the last filled row number in Column A. It retrieves it but I'm having trouble in using it as range and I get the error: Exception: Cannot convert 'Range' to int.
sourceSheet.getRange(rangeToCopy).copyTo(destination.getRange(destination.getRange(lastFilledRow,1), 1)),{contentsOnly:true};
The problem lies with your TARGET sheet having a set maximum row of 84, thus, destination.getLastRow()+1 will return 85 which is outside the said maximum row.
To solve this, create a new TARGET sheet or find a way to remove the limit in the current TARGET sheet. Your current code should be fine.
EDIT:
I've edited your v2 code to make it work on the current test sheet provided. Please see code below.
function CopyTo_V2(){
var sheet = SpreadsheetApp.getActive();
var sourceSheet = sheet.getSheetByName("SOURCE");
var destination = sheet.getSheetByName("TARGET");
var lastRow = sourceSheet.getDataRange().getLastRow();
var column = destination.getRange('A' + destination.getMaxRows())
for(var row=3; row<=lastRow; row++){
if(sourceSheet.getRange(row,1).getValue() == "" & sourceSheet.getRange(row,8).getValue() >= "45"){
Logger.log("CELL H"+row+" has \">=45\""+"\n=================\n"+"CELL A"+row+" is \"empty\""+"\n=================\n"+"RANGE TO COPY:\n"+ "\"G"+row+":G"+row+"\"");
var rangeToCopy = "G"+row+":G"+row;
var lastFilledRow = parseInt(column.getNextDataCell(SpreadsheetApp.Direction.UP).getA1Notation().slice(1))
Logger.log(lastFilledRow);
sourceSheet.getRange(rangeToCopy).copyTo(destination.getRange(lastFilledRow+1,1)),{contentsOnly:true};
destination.getRange(lastFilledRow+1, 9).setValue("Added Text Column 9");
destination.getRange(lastFilledRow+1, 13).setValue("Added Text Column 13");
destination.getRange(lastFilledRow+1, 14).setValue(new Date());
}
}
}

Exception: The starting row of the range is too small - Logs Numbers Why?

I have a basic script to take numbers from a sheet and use them to create a range, as well as using the last column function. I have had the error range is too small for the posting range.
When I log the output for both the column and row numbers these come out as expected!
I thought initially, it was because one was a last column pull and the other was pulling an integer from the cell in the sheets, as they were coming with decimal places, so I have overcome this with the conversion to number and then removing the decimals with the .tofixed() but this does not work either. Any ideas?
function weeklyData() {
var sourcess = SpreadsheetApp.openById('1B93Oq2s9Nou5hVgOb3y3t15t9xnqRMBnrYkAed-oxrE'); // key of source spreadsheet
var sourceSheet = sourcess.getSheetByName('Measures & Answers'); // source sheet name - change to your actual sheet name
var lr = Number(sourceSheet.getRange(2,3).getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow()).toFixed(0);
for(var i=0;i<lr+1;i++){
var dataValue = sourceSheet.getRange(i+2,3).getValue(); //This weeks numbers to update into table
var rowdataRange = sourceSheet.getRange(i+2,4).getValue(); //The row that the data needs to be pasted
var rowformat = Number(rowdataRange);
var row = rowformat.toFixed(0);
var pasteSheet = sourcess.getSheetByName('WHERE DATA ENDS UP'); // Data is to be pasted - change to your actual sheet name
var pasteColumn = pasteSheet.getRange(12,12).getDataRegion(SpreadsheetApp.Dimension.COLUMNS).getLastColumn()+1;
var column = pasteColumn.toFixed(0); // Column that is free for this weeks data
var pasteRange = pasteSheet.getRange(row,column,1,1);
Logger.log(pasteRange);
// pasteRange.setValue(dataValue);
}};
Your script works fine for me. I suspect this is an example script you've adapted from somewhere and trying to apply it to your data structure?
The reason you are getting the error is probably because the data in column 4 of your source sheet is not of number format? Either change your data or change the following line to the column containing numeric values.
var rowdataRange = sourceSheet.getRange(i+2,4).getValue();
This script is poorly written for this particular use.
You might want to check your Spreadsheet since it has lots of random values at random ranges.
When you use the following command Logger.log(pasteSheet.getLastColumn()); the number returned is 3753: which means that that is the next available column at which your data will be pasted.
The error message you were getting is due to the fact that the range was incorrect and you were passing wrong values in order to access it, which was most likely because of the values mentioned above.
Moreover, after cleaning all the unnecessary data, you can make use of the below script.
Snippet
function weeklyData() {
var spreadsheet = SpreadsheetApp.openById("ID_OF_THE_SPREADSHEET");
var sourceSheet = spreadsheet.getSheetByName("Measures & Answers");
var pasteSheet = spreadsheet.getSheetByName("WHERE DATA ENDS UP");
var valsToCopy = sourceSheet.getRange(2, 3, sourceSheet.getLastRow(), 1).getValues();
var rowsAt = sourceSheet.getRange(2, 4, sourceSheet.getLastRow(), 1).getValues();
var column = pasteSheet.getRange(12,12).getDataRegion(SpreadsheetApp.Dimension.COLUMNS).getLastColumn()+1;
for (var i = 0; i < valsToCopy.length; i++)
if (rowsAt[i][0] != "")
pasteSheet.getRange(parseInt(rowsAt[i][0]), parseInt(column)).setValue(valsToCopy[i][0].toString());
}
Explanation
The above script gathers all the data that needs to be copied as well as the rows associated with it. In order to make sure you don't end up using inappropriate values for the ranges, an if condition has been placed to make sure the value is not empty.
Reference
Sheet Class Apps Script - getLastColumn();
Sheet Class Apps Script - getRange(row, column, numRows, numColumns);

Get column to display month name Google App Script

How do I set a column to display the name of the month instead of the whole date using the script?
The function can manually be performed by selecting Format>Number>August in the menu but I want to do this in code.
This is what I've tried but I can't seem to find what I'm supposed to put in as the "format condition":
function myFunction() {
var spr = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spr.getSheets()[0];
var column = sheet.getRange("A:A");
column.setNumberFormats("Month"); // I'm pretty sure it's not supposed to be "Month" here, so what is it supposed to be?
}
Clarification; I want to set an entire column to change: 01/01/2015 to show January.
The error message I get on above code is "Cannot find method setNumberFormats(string)" and it's the same if i change "Month" to "L" or "MM".
A lot of typos in your script...(please be more careful when writing code and make use of autocomplete to check spelling : control+SPACE)
code goes like this :
function myFunction() {
var spr = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spr.getSheets()[0];
var column = sheet.getRange("A:A");
column.setNumberFormat("MMMM"); // MMM for abbreviated month, MM for month number
}

Moving rows to another google spreadsheet based on a condition

I'd like to know if its possible to move automatically rows to another Google spreadsheet based on a condition in editing (onEdit) the specific column entry that can be text, date, null or specific number.
I tried many times without being able to solve this puzzle.
Source (shared):
https://docs.google.com/spreadsheets/d/1Of4NUdvcxvCUWNSwpbkC4X8nqHpBetHCvyyiGqUPaJk/edit?usp=sharing
Destination (scripts) (shared):
https://docs.google.com/spreadsheets/d/1J7ChXoodQNg47LOrnp_GF-KLR1jKHxdDGmfAErVTP_U/edit?usp=sharing
Any help is appreciated. vagner
I'm getting an error on line 10 of your code:
This is what your current code looks like:
function onEdit(){
Logger.log("it ran!");
var ss = SpreadsheetApp.openById("1Of4NUdvcxvCUWNSwpbkC4X8nqHpBetHCvyyiGqUPaJk").getActiveSheet();
var ssd = SpreadsheetApp.openById("1J7ChXoodQNg47LOrnp_GF-KLR1jKHxdDGmfAErVTP_U").getActiveSheet();
Logger.log("ss: " + ss);
Logger.log("ssd: " + ssd);
var sheet1 = ss.getSheetByName('Source');
var sheet2 = ssd.getSheetByName('Destination');
Logger.log("sheet1: " + sheet1);
Logger.log("sheet2: " + sheet2);
There is a problem with these two lines:
var ss = SpreadsheetApp.openById("1Of4NUdvcxvCUWNSwpbkC4X8nqHpBetHCvyyiGqUPaJk").getActiveSheet();
var ssd = SpreadsheetApp.openById("1J7ChXoodQNg47LOrnp_GF-KLR1jKHxdDGmfAErVTP_U").getActiveSheet();
You should remove .getActiveSheet().
var ss = SpreadsheetApp.openById("1Of4NUdvcxvCUWNSwpbkC4X8nqHpBetHCvyyiGqUPaJk");
var ssd = SpreadsheetApp.openById("1J7ChXoodQNg47LOrnp_GF-KLR1jKHxdDGmfAErVTP_U");
That error was not showing up until I ran the code from inside of the code editor. And I needed to authorize some things for it to run for the first time.
I ran it in Debug mode.
When you chain the .getActiveSheet() method on the end, it returns the SHEET class, NOT the SPREADSHEET class. There are hierarchies of classes. The SHEET class is a lower level under the SPREADSHEET class. So, you were trying to use a method for the SPREADSHEET class, on a variable that contained a SHEET return type.