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()
Related
I have been trying to use a getlink function for extracting the URL of a hyperlink. The cell from which I need to extract a link is not configured with a hyperlink formula.
Screenshot Spreadsheet with link to URL (hovered above cell)
However when I use the script below, I always get:
*TypeError: Cannot read properties of null (reading 'getLinkUrl') (line 5). Why is that? *
The formula that I use for this function:
=GETLINK(CELL("Address";R2))
Script that I use:
function GETLINK(input){
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(input);
var value = range.getRichTextValue();
var url = value.getLinkUrl(0,1);
return url;
}
Modification points:
From your following sample image and your error message of TypeError: Cannot read properties of null (reading 'getLinkUrl'),
I thought that your current issue might be due to the number value. In the current stage, when the cell value is the number value, range.getRichTextValue() returns null. (This has already been reported to the Google issue tracker. Ref) In this case, an error like your error message is shown even when the cell has a hyperlink.
In order to remove this issue and retrieve the hyperlink, how about the following modification?
Modified script:
Please copy and paste the following script to the script editor of Google Spreadsheet and save the script.
In this modification, this script cannot be used as the custom function because of setNumberFormat. So, I proposed a sample script for retrieving the URLs from the source range and putting the URL into the destination range.
When you use this script, please set the values of srcRange and dstRange, and run the script by the script editor. By this, the script is run and retrieves the URL from srcRange, and the retrieved URLs are put to dstRange.
function sample() {
var srcRange = "Sheet1!A1:A10"; // Please set the source range you want to use.
var dstRange = "Sheet2!B1:B10"; // Please set the destination range you want to use.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange(srcRange);
var orgNumberFormats = range.getNumberFormats();
var values = range.setNumberFormat("#").getRichTextValues();
var urls = values.map(r => r.map(c => c && (c.getLinkUrl() || "")));
range.setNumberFormats(orgNumberFormats);
ss.getRange(dstRange).setValues(urls);
}
When this script is run, the number formats of srcRange are saved, the cell values are converted to the string values, and the rich text values are retrieved from srcRange. And then, the URL is retrieved and the URLs are put to dstRange.
Note:
In the case that your error is removed from your showing script, the following script can be used. But, in this case, when the cell value is the number value, no value is returned even when the cell has a hyperlink. Please be careful about this.
function GETLINK(input) {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange(input);
var value = range.getRichTextValue();
return value && value.getLinkUrl(0, 1);
}
References:
map()
getNumberFormats()
setNumberFormats(numberFormats)
I have this formula that extracts the link from a word with hyperlink. Now when I'm trying to move it to another spreadsheet and run it I get an 'Exception: Range not found' error. I was reading this might be cuz I need a 'getRangeList' insted of getRange, but it doesn't work this way either. Now I get the 'Exception: The parameters (number) don't match the method signature for SpreadsheetApp.Sheet.getRangeList.'
Here's the code I'm using:
function URL(refrence) {
var sheet = SpreadsheetApp.getActiveSheet();
var formula = SpreadsheetApp.getActiveRange().getFormula();
var a1 = formula.replace("=url(","");
a1 = a1.replace(")","");
var url = sheet.getRange(a1).getRichTextValue().getLinkUrl();
return url
}
FINDINGS
The part getRange(a1) is incorrect as the variable a1 contains an invalid Sheet range.
SUGGESTION
If your main goal is to easily extract the URL from a cell with hyperlink like =HYPERLINK("http://www.google.com/","Google") you may use these tweaked scripts below:
These scripts were derived from the answers of these posts How to extract URL from Link in Google Sheets using a formula & Google Apps Script Regular Expression
This version of the script will only show the url value from the Apps Script editor's log results:
function URL() {
var sheet = SpreadsheetApp.getActiveSheet();
var formula = sheet.getActiveRange().getFormula();
var regExp = new RegExp("\"(.*)\",\"", "gm");
var url = regExp.exec(formula)[1];
Logger.log(url)
}
Note: Before running, make sure the cell with hyperlink is selected on your sheet (in my case it was on cell A1).
Sample result on the logs:
This another version will let you to use your script as a custom function =URL() on your spreadsheet file:
function URL(refrence) {
var regExp = new RegExp("\"(.*)\",\"", "gm");
var url = regExp.exec(refrence)[1]
return url
}
Sample Result as a custom function:
=URL(FORMULATEXT(A1))
Reference:
FORMULATEXT function
With google apps script:
function myFormula() {
var sheet = SpreadsheetApp.getActive();
// var currentCell = SpreadsheetApp.getActiveSheet().getCurrentCell();
// var activeCell = SpreadsheetApp.getActiveSheet().getCurrentCell();
// this what I would want:
var theCellWhereFunctionIs = SpreadsheetApp.getActiveSheet().getCellWhereFormualIs(); // this what I would want..
}
Q: How to get function's cell (not current and not active cell) with Google Apps script
the theCellWhereFunctionIs
So if I place "=myFunction()" to A1 so myFunction would know that it's A1, getting the cell object of it.
--
If it's not possible. I know I can pass the range to myFunction, like this =myFunction("A1"), where "A1" is current cell/range where that function is.
But then problem is that that "A1" is hard-coded. I wonder what I can do about it? I ve checked on some answers in SE, but couldn't find cleat on.
I can't do this myFunction(A1) because it pass value, not reference to range/cell object. There is something about &A1?
Code:
function getCell(formula) {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange();
var formulas = range.getFormulas();
formula = sheet.getRange(formula).getFormula();
for (var i = 0; i < formulas.length; i++) {
if(formulas[i].indexOf(formula) > -1){
return sheet.getRange(i+1,formulas[i].indexOf(formula)+1).getA1Notation();
}
}
}
Sample Data:
Sample Formula:
A1 => =sequence(5)
B1 => =query(A1:A5, "where A > 3")
A10 => =query(A1:A5, "where A > 3")
Output:
Behaviour:
It gets the whole range of the sheet via getDataRange
Fetches all formulas within the range
Loops into each cell and then check if the formula where the parameter points out is present.
In case of multiple expected results, this will only return the first cell encountered.
Sheets:
In Sheets, address is a function that can be used to return what the A1 notation of the cell is. This might be helpful to you.
Output:
If I misunderstood what you meant, I sincerely apologize. It would be nice if you could also provide an illustration how it would behave like shown above and how the output would be used so we will not misunderstood your goal and intentions.
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?
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.