How to get Value from a cell with formula? - google-apps-script

I have a formula in a cell (18,2) which is =(B17-B14)*B15+B17. So what you see if a numeric value. But when I tried to use the following script to fetch the value to a new cell, it put #num in the new cell. I tried other cells with formulas, when it is a simple formula, (b+c) for example, the getValue() works. But not this one. Why? Thank you for your help in advance!
function myfunction1 ()
{
var app=SpreadsheetApp;
var ss=app.getActiveSpreadsheet();
var activeSheet=ss.getActiveSheet();
var range = activeSheet.getRange(18,2);
var fstave=range.getValue();
// retrieve value
activeSheet.getRange(8,8).setValue(fstave);
Logger.log("Value: " + fstave);
}

You shold be able to use getDisplayValue() for the effect you want.

Related

Google-sheet function for cell above in costumized formula

I am trying to create a function/formula/script in Google sheets for my own formula.
I have one, where I need the value displayed in the cell above, which I type in manually. The formula is 5.5^(39-XX). So if for example cell B5 has the value 32, in cell B6 I'd like to type something like "=MYFORMULA" into the cell where the calculated value should be displayed. MYFORMULA should be programmed as 5.5^(39-cellabove).
I have already tried
function MYFORMULA() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var cellRange = sheet.getActiveCell();
var selectedColumn = cellRange.getColumn();
var selectedRow = cellRange.getRow();
Logger.log(`selectedColumn: ${selectedColumn}`);
Logger.log(`selectedRow: ${selectedRow}`);
Logger.log(`selected cell vale: ${cellRange.getValue()}`);
cellRange.setValue('=5.5^(39-(MYFORMULA[-1;]))')
}
which does not work, unfortunately. I have the feeling, I have to program a function for the current cell as well. Any suggestions for the code? I am coding into Apps Script in Google tables.
Also, I have to activate a trigger in order to have premission using any newly created function. If you have any suggestions here, too, I would appreciate your help.
Cheers!
Rather than detect the active range and set a value directly, you can implement MYFORMULA as a custom function, which can take an input that you pass as a cell reference and return a value, which will be written into the cell containing the formula.
Suggested change
Change your function to include an input variable, and to return a value, without any reference to specific cells, like this:
function MYFORMULA(x) {
return 5.5**(39-x)
}
(Note ** is the Javascript symbol for exponent)
Then, in your spreadsheet, in cell B6, type =MYFORMULA(B5). The spreadsheet will pass the value in B5 to your function, and will write the return value in B6.

Google Sheets Apps Script, return random item from named range

I'm trying to create a custom function that I can give a name range as input and have it output a random item from the name range. I have multiple named ranges so it would be convenient to have one function that I could use for all of them. This is what I'm trying to replace =INDEX(named_range,RANDBETWEEN(1,COUNTA(named_range)),1)
This is what I've tried but it doesn't work:
function tfunction(n) {
var randomstuffs = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n);
var randomstuff = randomstuffs[Math.floor(Math.random()*randomstuffs.length)];
Logger.log(randomstuff);
}
Thanks in advance
You can try this edited script:
function tfunction(n) {
//randomstuffs will only get all cell data that are not empty from a named range
var randomstuffs = [].concat.apply([], SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n).getValues()).filter(String);
var randomstuff = randomstuffs[Math.floor(Math.random()*randomstuffs.length)];
return randomstuff;
}
Sample Result
Created a sample named range TestRange on Column A with 21 cells of data then tried the custom function =tfunction("TestRange") which returned a random cell value.
.getRangeByName() method returns a reference to a range, not the values in the range. You need to add .getValues() to it:
var randomstuffs = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n).getValues();
Also keep in mind that .getValues() method returns a 2D array of values, indexed by row, then by column. So your var randomstuff declaration will need to be change to account for that, depending on how many rows and columns your range has.

copy+paste displayed values Google Sheet

I have a column with formatted ids (Brazilian CPF).
The user input is 12345678900 and the displayed value is 123.456.789-00.
If I copy and paste this column to another column, the values pasted are in 12345678900 format.
I want to copy the "displayed values" of a column to another column using google script what's the simple code for that?
I am trying using a loop, but my sheet is too big and it is very slow!
Updating cell with the displayed value format is not working.
while (primeira_linha <= ultima_linha){
var cpf_formatado = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("2020").getRange(primeira_linha,10).getDisplayValue();
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("2020").getRange(primeira_linha,10).setValue(cpf_formatado);
primeira_linha++;
You want to get values from the column "J" on the sheet of 2020 in the active Spreadsheet using getDisplayValue.
You want to put the retrieved values to the other column as the text.
You want to reduce the process cost of your current script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification point:
In your script, getDisplayValue and setValue are used in the loop. By this, the process cost becomes high.
Pattern 1:
In this pattern, in order to reduce the process cost, getDisplayValues and setValues are used without using the loop. So the values are retrieved as the text values, and put them as the text values.
Modified script:
When your script is modified, it becomes as follows. Before you run the script, please set the variables.
var primeira_linha = ##; // Please set the start row.
var ultima_linha = ##; // Please set the end row.
var sourceColumn = 10; // Source column. In this case, it's the column "J".
var destinationColumn = 10; // Please set the column you want to put the values. In this case, it's the column "J".
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("2020");
var values = sheet.getRange(primeira_linha, sourceColumn, ultima_linha - primeira_linha + 1).getDisplayValues();
sheet.getRange(primeira_linha, destinationColumn, values.length, 1).setNumberFormat("#").setValues(values);
From your script, it seems that the values retrieved with getDisplayValues from the column "J" are put to the same column. So the above modified script is the same process.
And in this case, in order to modify the cell format, I used setNumberFormat("#"). In this case, the values are put as the text. If you don't want to modify the cell format. Please remove .setNumberFormat("#").
Pattern 2:
In this pattern, copyTo is used. In this case, the values are copied with the cell format.
Modified script:
var primeira_linha = ##; // Please set the start row.
var ultima_linha = ##; // Please set the end row.
var sourceColumn = 10; // Source column. In this case, it's the column "J".
var destinationColumn = 10; // Please set the column you want to put the values. In this case, it's the column "J".
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("2020");
var sourceRange = sheet.getRange(primeira_linha, sourceColumn, ultima_linha - primeira_linha + 1);
var destinationRange = sheet.getRange(primeira_linha, destinationColumn);
sourceRange.copyTo(destinationRange);
References:
getDisplayValues()
setValues()
setNumberFormat()
copyTo(destination)
If I misunderstood your question and this was not the direction you want, I apologize.

Use google apps script to increment a column on Google Sheets by 1?

Not sure how to go about incrementing the number values on my google spreadsheet by 1 with a button, the script I'm using only increments the first cell and copies that down. How can I make the script increment the whole column and it's individual cells by 1?
function increment(){
var cell = SpreadsheetApp.getActiveSheet().getRange("C2:C86");
var cellValue = cell.getValue();
cell.setValue(cellValue + 1);
}
You want to add 1 to the cells of "C2:C86".
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modified script:
function increment(){
var cell = SpreadsheetApp.getActiveSheet().getRange("C2:C86");
var cellValues = cell.getValues().map(function(row) {return [row[0] + 1]}); // Modified
cell.setValues(cellValues); // Modified
}
Flow:
Retrieve the values from the cells of "C2:C86".
Add 1 for the value of each cell.
Put the values to the range of "C2:C86".
References:
getValues()
setValues()
map()
If I misunderstood your question and this was not the result you want, I apologize.

How to get fixed cell value, not formula?

I have a cell in Google Sheets, with =NOW() formula in it. All I need - to get the value, generated by formula (22.01.2014 15:23:51), not the formula by itself.
If I try: var nowtime = SpreadsheetApp.getActiveSheet().getRange('A1').getValues();,
I get ={DATE(2014\1\22)+TIME(15\19\13)}, but not the numbers.
How to do it with Google Script syntax?
I know I'm a little late to the party here, but you could try .getDisplayValue() instead of .getValue() or .getDisplayValues() instead of .getValues() That will give you the result of the formula instead of the formula itself.
I just had the same problem and the above solution worked for me.
Use this little snippet to do that.
Code
function getCell(startcol, startrow) {
// prepare string
var str = String.fromCharCode(64 + startcol) + startrow;
// retrieve value
var vCell = SpreadsheetApp.getActive().getRange(str).getValue();
// return content cell
return vCell;
}
Screenshot
Explained
The first parameter of the custom function passes on the column index, as an integer. The var str creates from the column integer and the row index a string (A1 notation). Then the value is retrieved and returned to the spreadsheet.
This piece of code will retrieve any value.
Add the script under Tools>Script editor. Press the "bug" button to validate the script and you're on the go !!