Convert a string to a formula in Google Spreadsheet - google-apps-script

I´d been more than 10 hours reading and trying different options with no success.
I have this string (this is actually a string that is generated by other formulas)
QUERY({IMPORTRANGE(A1;$D$1);IMPORTRANGE(A2;$D$1);IMPORTRANGE(A3;$D$1);IMPORTRANGE(A4;$D$1)};"select Col13, sum(Col1), sum(Col2), sum(Col3), sum(Col4), sum(Col5), sum(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12) group by Col13";0)
And I want it to be read as a formula.
So for example I try this function:
function doConvert(formula) {
// Strip leading "=" if there
if (formula.charAt(0) === '=') formula = formula.substring(1);
return eval(formula);
}
But I get:
Error / SyntaxError: Falta ":" detrás del ID de propiedad.
(In English would be: ":" missing after property ID.
Any other solution would be great.

add = to your generated string and try like this:
function onEdit() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet_Name_Here');
var src = sheet.getRange("A1"); // The cell which holds the formula
var str = src.getValue();
var cell = sheet.getRange("C5"); // The cell where you want the results to be in
cell.setFormula(str);
}

Google Sheets formulas can't be evaluated on the server/client code, only on the Google Sheets UI.
If you are looking that your string be passed as a formula to a cell, then use the setFormula(formula) method from the Class Range
NOTE: there is no need to preppend the equal sign to the formula.
Example
Assuming that the formula string is in A1 and that you want to put is as formula in B1
function setFormula(){
var sheet = SpreadsheetApp.getActiveSheet();
var source= sheet.getRange('A1');
var formula = source.getValue();
var target = sheet.getRange('B1');
target.setFormula(formula);
}
Related
Is there a way to evaluate a formula that is stored in a cell?
How to evaluate a spreadsheet formula within a custom function?

Related

What is VBA's format function equivalent in Google Scripts/Sheets?

I'm having some trouble to achieve next VBA code's goal in Google Scripts (changing the number format of a variable adding zeros at the left up to figures)
'VBA CODE
sub addingZeros()
dim num1 as double
'Cell A1's value is 1, so I get 0001
num1 = format(thisWorkbook.Sheets("MySheet").range("A1"),"0000")
end sub
When I was researching, everything pointed out to use the setNumberFormat function, which is not a solution for me, because makes me to change the number in the sheet and I need only to change the variable value for further purposes... There was only one different solution in those I found, which uses a text function but I couldn't make it work (link for that solution)
I'd like a code similar to this:
//Google Scripts CODE
function myFunction() {
var ss = SpreadsheetApp.openById(`XXXXXXXXXXXXX`);
var sheet = ss.getSheetByName('MySheet');
var num1 = format(sheet.getRange('a1').getValue(),"0000");
//Cell A1's value is 1, so I'm expecting to get 0001
Logger.log(num1);
};
All the help will be much appreciated.
Antonio
I believe your goal as follows.
You want to retrieve a value from a cell and you want to convert the format from 1 to 0001.
You want to achieve this using Google Apps Script.
Pattern 1:
In this pattern, Utilities.formatString is used.
Sample script:
function myFunction() {
var ss = SpreadsheetApp.openById(`XXXXXXXXXXXXX`);
var sheet = ss.getSheetByName('MySheet');
var res = Utilities.formatString("%04d", sheet.getRange("A2").getValue()); // Modified
Logger.log(res)
}
In this modification, the value of 1 is retrieved from the cell "A1" and the format is converted to 0001 using Utilities.formatString.
Pattern 2:
In this pattern, setNumberFormat is used.
Sample script:
function myFunction() {
var ss = SpreadsheetApp.openById(`XXXXXXXXXXXXX`);
var sheet = ss.getSheetByName('MySheet');
var res = sheet.getRange("A1").setNumberFormat("0000").getDisplayValue(); // Modified
Logger.log(res)
}
In this modification, the format of cell "A1" is changed using setNumberFormat and retrieved the display value using getDisplayValue.
Note:
These modified scripts are the simple modification. So please modify them for your actual situation.
References:
formatString(template, args)
setNumberFormat(numberFormat)
getDisplayValue()

Google Apps Script - copy a formula from one cell to another incrementing A1 notation in new cell

When, in a google sheet, you click on a cell and in the bottom corner of the cell, drag the blue icon to the next cell, the formula goes with it and increments the A1 notation appropriately. getFormula() and setFormula() don't do this. Anyone know the function or steps to accomplish this?
function increment() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1];
//Can this be used to increment A1 notation when setting a formula in another cell?
// var cellNotation = sheet.getRange(1,1).getA1Notation();
sheet.getRange(1,2).setFormula("=G11 + (F12*(1 +$C$3) )");
}
You can use setFormulaR1C1(formula) which updates the formula for the given range:
function increment() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1];
var formula = sheet.getRange(1,1).getFormulaR1C1();
sheet.getRange(1,2).setFormulaR1C1(formula);
}
Be careful:
The formula argument in setFormulaR1C1 needs to be in R1C1 notation.
For example, the formula: =G11 + (F12*(1 +$C$3) ) is written in R1C1 notation as
=R[10]C[6] + (R[11]C[5]*(1 +R3C3) )
You don't need to construct the R1C1 notation manually. You can use getFormulaR1C1() (like the code I provided) to get the R1C1 notation of a cell.
getFormulaR1C1() returns null if there is no formula in the selected range.

How to use variable columns inside my formula in Google Apps Script?

I'm trying to include variable columns inside my formula in Google Apps Script. I only have the numbers of these columns as information - defined as input values on another sheet. And the input value can be changed. For example: I don't want to have "G1" in the formula, but present it through its column number 7. Below is a simple representation of what I'm trying to achieve.
function variableColumn() {
var report = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = report.getSheetByName('Test');
var inputSheet = report.getSheetByName('Input');
// Current stored value in "A1" is 7 (corresponding to the "G" column)
var firstColRange = inputSheet.getRange("A1");
var firstColValue = firstColRange.getValues();
// Current stored value in "A2" is 8 (corresponding to the "H" column)
var secondColRange = inputSheet.getRange("A2");
var secondColValue = secondColRange.getValues();
var range = sheet.getRange("A1");
range.setFormula('=G1 + H1');`
What I'm expecting as a final result is to present "G1" and "H1" through their column numbers stored on the 'Input' sheet, i.e. through the variables: firstColValue AND secondColValue. Because next time I may want to have ('=P1 + T1').
Many thanks in advance!
Problem
The OP is trying to use variables in the construction of a formula to be assigned by setFormula.
This is not a new topic; e.g. refer SpreadsheetApp how to use variable inside formula or Google App Script: Trying to setFormula for Spreadsheet cell. What sets the OP's problem apart is that the OP doesn't want to use a variable name, as such, but rather a value that is a reference to a column.
Solution
Cell A1 and A2 each contain a number that denotes a column number. Those numbers need to be changed to letters for inclusion in the formula. The subroutine columnToLetter(column) is an efficient way of doing this.
The formula is inserted on the "Test" sheet. This requires that the "Input" sheet name must be included in the formula. I have shown two options for how the sheet name can be obtained: 1) from a variable value; and 2) using getSheetByName().getName().
The formula can be built directly into setFormula, or as a variable that is assigned to setFormula. The benefit of the latter approach is that, during development, a Logger statement can be used to display the output of the formula. Both options are included in the code.
On "Escaping Characters"
In the OP's scenario, the sheets are single words and the formula is no so complex as to include characters such as spaces, commas, colon, or forward slash. The effect is that no characters need be escaped. If this were not the case, then it would be necessary to escape some characters, in which case this brief note on Escaping Characters, and the code example on that topic, may be helpful.
function so5473414301() {
// setup spreadsheet
var report = SpreadsheetApp.getActiveSpreadsheet();
// define sheets
// Note: two ways to refer to a sheet name
// 1 = put the name in a variable -> then getSheetByName(variable)
// 2 = put the sheet name in method -> report.getSheetByName('Input'). Then get name using .getName()
var mainSheetName = "Test";
var mainSheet = report.getSheetByName(mainSheetName);
//Logger.log("DEBUG: mainsheet name:"+mainSheet.getName()); //DEBUG
var inputSheet = report.getSheetByName('Input');
var inputSheetName = inputSheet.getName();
//Logger.log("DEBUG: inputheet name: "+inputSheet.getName()); //DEBUG
// Current stored value in "A1" is 7 (corresponding to the "G" column), and convert to the equivalent column letter
var firstColRange = inputSheet.getRange("A1");
var firstColValue = firstColRange.getValues();
//Logger.log("DEBUG: fircolRange = "+firstColRange.getA1Notation()+", value = "+firstColValue); //DEBUG
// get the columnletter for that column number
var firstcolname = columnToLetter(firstColValue)
//Logger.log("DEBUG: firstcolname = "+firstcolname); //DEBUG
// Current stored value in "A2" is 8 (corresponding to the "H" column), and convert to the equivalent column letter
var secondColRange = inputSheet.getRange("A2");
var secondColValue = secondColRange.getValues();
//Logger.log("secondColRange = "+secondColRange.getA1Notation()+", value = "+secondColValue);
// get the columnletter for that column number
var secondcolname = columnToLetter(secondColValue);
//Logger.log("DEBUG: secondcolname = "+secondcolname); //DEBUG
// define the location for the formula
var outputrange = mainSheet.getRange("A3");
// construct the formula
// The formula should output as '=Input!G1+Input!H1
// Note 2 options here
// 1 - Build the formula straight into the `setFormula`
// 2 - Build the formula and assign it to a variable, then use the variable in the `setFormula`
// Option#1
//outputrange.setFormula("="+inputSheet.getName()+"!"+firstcolname+"1+"+inputSheet.getName()+"!"+secondcolname+"1");
// Option#2
// Build the formula - Looger will show the formula as converted.
var formula = "="+inputSheet.getName()+"!"+firstcolname+"1+"+inputSheet.getName()+"!"+secondcolname+"1";
Logger.log("DEBUG: The formula is: "+formula);//DEBUG
// set the formula in the outputrange
var output = outputrange.setFormula(formula);
}
function columnToLetter(column)
{
var temp, letter = '';
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
Summary of cell and formula values
Credit
"columnToLetter" (plus "letterToColumn" not included here)
AdamL (https://stackoverflow.com/a/21231012/1330560)

Need help Google Apps Script and sheet: Building a custom function for Google spreadsheet to Copy/Paste Value

I'm building a function to get Value from another cell. It will work this way:
At cell A1, I place function = copyValue(B1) or = copyValue(1 , 2) so that custom function will return the value of B1.
Here is my code:
function copyValue(int a,b) {
var ss = SpreadsheetApp.openById('1HTEuyd7po43VKM37nmzCvPgLEVESgcN5YpAu2VRTiFI');
var sheet = ss.getSheetByName("Total");
var cell = sheet.getRange(a,b);
var c = cell.getValue();
return(c);
}
But when I run, it said:
[quote]Missing ) after formal parameters. (line 1)[/quote]
if I remove "int" before the formal params, it said I cannot getRange NULL.
Please help me to fix this. Thanks
You can make your function much simpler if all you are trying to do is get the value of a cell.
function copyValue(cell) {
return cell;
}
Then in your sheet just do =copyValue(B1) and whatever your value is in B1 will be returned into the cell.

Google sheets custom function argument address for conditional formatting

I'm writing a custom function in Google Sheets with intention of using it for conditional formatting:
function f(cellValue) {
}
How can i get the address of the cell whose value i get in the cellValue argument?
The function should return true if the three cells above the given one are empty.
As far as I know, you can't do it directly.
But your function could take 2 more arguments:
function f(cellValue, rowNum, columnNum) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(rowNum, columnNum);
var address = range.getA1Notation();
return address + " = " + cellValue;
}
Example of the usage of the formula:
= f(A1, row(A1), column(A1))
So we use native functions (row & column) inside custom formula.
OK, let's talk about your task.
The function should return true if the three cells above the given one are empty.
You may use this formula (no script needed):
=join("",OFFSET(B63,-3,,3))=""