Replace function with text in specific cell - Apps script - google-apps-script

I tried to use the following code to replace the current cell formula with test text instead.
function replace_content() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
cellRange.setValue("test")
return true
)
But something goes wrong and I get this error msg
Error
Exception: You do not have permission to call setValue (line 59).
Please advice.

This function runs for me with no problems:
function replace_content() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
cellRange.setValue("test")
return true;
}

Related

Script to copy a changing range to cell B2

I am trying to write a script to copy a range of cells to cell B2. The range to copy from changes each time so want to highlight the top left cell and then the script takes it from there. What I have so far is:
function CopyToB2() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
var selectedColumn = cellRange.getColumn();
var selectedRow = cellRange.getRow();
var range = SpreadsheetApp.getActiveSheet().getRange(selectedColumn,selectedRow,2,43);
range.setValues(range);
spreadsheet.getRange('B2').activate();
(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};
but get the error
Exception: The parameters (SpreadsheetApp.Range) don't match the
method signature for SpreadsheetApp.Range.setValues
Explanation:
The main issue with your code is that you pass a range object in the setValues function and therefore you are getting this error.
A second issue is that you passed the parameters of the getRange(row, column, numRows, numColumns) function in the wrong order. It should be:
getRange(selectedRow,selectedColumn,43,2)
instead of getRange(selectedColumn,selectedRow,2,43)
A third issue is that you need to define the range that the data will be pasted to and that can't be just a single cell B2 in this case. What you need to do is to define B2 as the start of your pasting range and then set the values of your active range.
Solution:
function CopyToB2() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
var selectedColumn = cellRange.getColumn();
var selectedRow = cellRange.getRow();
var dataRange = sheet.getRange(selectedRow,selectedColumn,43,2).getValues();
sheet.getRange(2,2,dataRange.length,dataRange[0].length).setValues(dataRange);
};

Trigger a function when one cell is edited in Google Sheets

after some hours of reading documentation and other answers I couldn't solve my problem.
I'm trying to trigger a formula when one cell is edited. I get it to run when I just ask a value to be set (see commented line in the code) but not when I call another formula.
Here's the script:
function onEdit() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cell = sheet.getActiveCell();
var row = cell.getRow();
var column = cell.getColumn();
if ( row ===1 && column ===4 && sheet.getName() ==="Hoja 1" ) {
sendData();
//sheet.getRange(1,1).setValue("5");
}
function sendData() {
var sheet = SpreadsheetApp.openById("1pxS9F9YEagzzRyTOqIDGVpDaCEiY_Z1DOYxq1QVzWGk");
var source_sheet = sheet.getSheetByName("Hoja 1");
var target_sheet = sheet.getSheetByName("Hoja 2");
var range1 = source_sheet.getRange(1, 7, 6, 1).getValues();
target_sheet.getRange(1,1,6,1).setValues(range1);
}
}
You have to pass the sheet into the called function this way:
sendData(spreadsheet);
function sendData(sheet) {
...
}
onEdit() is a simple trigger. Simple triggers cannot access services that require authorization. So it cannot call SpreadsheetApp.openById().
https://developers.google.com/apps-script/guides/triggers#restrictions
And pay attention -- in the function sendData() you're using the name sheet but it's a spreadsheet actually. This is not an error but it can be confusing a bit.

How do I extract a google sheet named range's column number via Google Script?

I need to enter data in a Google sheet cell, which cell is in a named range. To do that using a Google Script, I need to know the named range's column number. I have written a script that gets the job done, but only because I know the named range has only one column, so I use the getLastColumn command to get the column number. I know there has to be a command to "getColumnNumber" or something like that, but from Google documentation and this site, I simply can't find it. Any help? Bound script below:
function addSong() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var lastRow = sheet.getLastRow()
sheet.appendRow([lastRow+1]);
SpreadsheetApp.flush();
var range = sheet.getRange(sheet.getLastRow(), 1);
var songTitle = Browser.inputBox('New Song', 'Enter the song title', Browser.Buttons.OK_CANCEL);
var namedRange = sheet.getRange("Title");
var col = namedRange.getLastColumn();
sheet.getRange([lastRow+1], col).setValue(songTitle)
SpreadsheetApp.setActiveRange(range);
}
Hey Cooper: I tried your approach and it works great, except it loses some of what I was doing with my script; specifically, it does not increment the song record number. So, I added the key bit from what you did to get the named range column correctly into my code and it all works. Revised code is:
function addSong() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var lastRow = sheet.getLastRow()
sheet.appendRow([lastRow+1]);
SpreadsheetApp.flush();
var range = sheet.getRange(sheet.getLastRow(), 1);
var songTitle = Browser.inputBox('New Song', 'Enter the song title', Browser.Buttons.OK_CANCEL);
var namedRange = sheet.getRange("Title");
var range=sheet.getRange(sheet.getLastRow(), namedRange.getColumn())
range.setValue(songTitle);
SpreadsheetApp.setActiveRange(range);
}
Try this:
function addSong() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var resp=SpreadsheetApp.getUi().prompt('New Song', 'Enter the sone title', SpreadsheetApp.getUi().ButtonSet.OK_CANCEL);
var songTitle=resp.getResponseText();
var namedRange = ss.getRangeByName('Title');
var range=sh.getRange(sh.getLastRow()+1, namedRange.getColumn())
range.setValue(songTitle);
SpreadsheetApp.setActiveRange(range);
}
range.column documentation

Google Sheets Add-On onEdit(e) not working with Enabled Document

I am trying to to create an Add On where the user has the option to either choose from the menu, or an onEdit command triggers a change to the cell in sheets. When I use the code below, attached to the sheet it works perfectly, however, when i test it as AUTH-LIMITED (Enabled or installed & enabled) the onEdit(e) functionality doesn't work. Everything about the menu button is working great, I can't figure out how to get the onEdit(e) called, what so ever.
I've tried searching all over but to no success with how to solve for this specific issue.
Thank you in advance!
function onEdit(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheeter = ss.getActiveSheet();
sheeter.getRange("a1").setValue("Test");
var range = e.range;
var val = range.getValues();
if(val.length+val[0].length<=2){
var val = range.getValue();
if(range.getFormula()){}
else{
var regex2 = new RegExp('[0-5]{0,1}[0-9]:[0-5]{0,1}[0-9].[0-5]{0,1}[0-9]$','g');
var docContent2 = val.replace(regex2,"00:"+val);
range.setValue(docContent2);
range.setNumberFormat("[M]:SS.0");
}
}
}
function Mass_Convert(){
var now = Date.now();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getActiveRange();
var val = range.getValues();
var replaceBox = new Array(val.length);
var replaceFormat =range.getNumberFormats();
for(var i=0;i<val.length;i++){
replaceBox[i] = new Array(val[i].length);
replaceFormat[i] = new Array(val[i].length);
for(var j=0;j<val[0].length;j++){
var newRange = range.getCell(i+1,j+1);
var newVal = newRange.getValue();
var format = newRange
if(newRange.getFormula()){
replaceBox[i][j]=newRange.getFormula();
replaceFormat[i][j] = newRange.getNumberFormat();
}
else{
if(isNaN(newVal)){
var regex2 = new RegExp('[0-5]{0,1}[0-9]:[0-5]{0,1}[0-9].[0-5]{0,1}[0-9]$','g');
var docContent2 = newVal.replace(regex2,"00:"+newVal);
replaceBox[i][j] = docContent2;
replaceFormat[i][j] = "[M]:SS.0"
}else{
replaceBox[i][j] = newVal;
replaceFormat[i][j] = newRange.getNumberFormat();
}
}
}
}
range.setValues(replaceBox);
range.setNumberFormats(replaceFormat);
}
function onOpen(e) {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Split Conversion')
.addItem('Mass Convert Selected', 'Mass_Convert')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
I tested this with my add-on and .getActiveSpreadsheet() gives the error:
Execution failed: The Add-on attempted an action that is not permitted in Test as Add-on mode. To use this action, you must deploy the Add-on
Also your onEdit() might have permission issues. There should be some condition to run on specific sheets otherwise it will run on all sheets.
I also found this:
onEdit(e) not working in Add-on

HTTP Get in Google Spreadsheet, "e undefined"

I'm trying to use HTTP Get in Google Spreadsheet, to be able to create a URL to a specific cell in a sheet. I've been searching for how to do it, and I've tried using this way (the GET part), for example.
Here's the code I've put together:
function doGet(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Kunder");
var row = e.parameter["row"];
var col = e.parameter["col"];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange(row, col);
SpreadsheetApp.setActiveSheet(sheet);
SpreadsheetApp.setActiveRange(range);
}
And this is an example URL:
https://docs.google.com/spreadsheets/d/[spreadsheet ID]/edit?row=5&col=1
When I run the script I get this error:
TypeError: Cannot read property "parameter" from undefined.
I'm I doing something wrong? Or isn't it possible?
Thanks in advance,Oskar
EDIT
This is my current code:
function doGet(e){
var ss = SpreadsheetApp.openById("[id]");
SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = ss.getSheetByName("Kunder");
var row = Number(e.parameter.row);
var col = Number(e.parameter.col);
var range = sheet.getRange(row, col);
SpreadsheetApp.setActiveSheet(sheet);
SpreadsheetApp.setActiveRange(range);
}
The code runs but finishes with
The script completed but did not return anything.
I want to open the spreadsheet and then set the active range from the GET parameters.
The url you show is not valid.
To use that kind of script you have to deploy the script as a webapp and use the resulting .exec url with parameters.
At the end it will look like this :
https://script.google.com/macros/s/AKfycbygwUwXXXXXXXXxJcKpBvsbflmnZ0Uqfu-JISWTZNvar32s3v_hl/exec?row=5&col=1
EDIT : there will be no activeSheet in that context, use openById or openByUrl instead.
Also the values you get for row and columns are strings, you should make them integers and use a normal sheet.getRange(row,col) to select a range.
EDIT2 :
this url :
https://script.google.com/macros/s/AKfycbwZbGW6E483BUplvLjCjNCXKjjiRorqzR9lruSydogeuU-YIvID/exec?row=1&col=1
and this code :
function doGet(e){
var ss = SpreadsheetApp.openById("1sbJXuEpL_88-u-Bm4QOCAM3SVddFwZKI0c1kxeRpcos");
var sheet = ss.getSheetByName("Sheet1");
var row = Number(e.parameter.row);
var col = Number(e.parameter.col);
var range = sheet.getRange(row, col);
sheet.getRange(row, col).setValue('test ok')
}
writes in this sheet : see cell A1 or test on another row and column.
You'll indeed receive a message that nothing was returned and this is actually true ! we don't return anything in that code, this is just a demo ;-)
EDIT 3 : as mentioned in the comments, to get something returned by this function you have to resturn something...
Here is an example :
function doGet(e){
var ss = SpreadsheetApp.openById("1sbJXuEpL_88-u-Bm4QOCAM3SVddFwZKI0c1kxeRpcos");
var sheet = ss.getSheetByName("Sheet1");
var row = Number(e.parameter.row);
var col = Number(e.parameter.col);
var range = sheet.getRange(row, col);
var value = sheet.getRange(row, col).getValue();
sheet.getRange(row, col).setValue('test ok');
var stringValue = value==''?'empty':value;
Logger.log(stringValue);
return ContentService.createTextOutput(stringValue).setMimeType(ContentService.MimeType.TEXT);
}