Format a Google Sheets cell in numerical formatting 000 via Apps Script - google-apps-script

I'm looking to set a column to format 000, which will display the zeros at begenning.
So, if a cell displays "3", I want that the script will set it to display "003".
This column is located in BDD tab, 13th column starting from the second row.
function FormattingGpeTrait() {
const sheet = SpreadsheetApp.getActiveSheet().getSheetByName("BDD").getRange(2,13)
sheet.setNumberFormat('000')

Modification points:
The method of "getSheetByName" is for Class Spreadsheet. In your showing script, you try to use it to Class Sheet. By this, an error occurs. This has already been mentioned in the comment. Ref
From 13th column starting from the second row., I thought that you might have wanted to set the number format of 000 to "M2:M". In your showing script, the number format is set to only a cell "M2".
If you want to set the number format to the cells "M2:M" of the sheet name of "BDD", how about the following modification?
Modified script:
function FormattingGpeTrait() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BDD");
sheet.getRange("M2:M" + sheet.getLastRow()).setNumberFormat('000');
}
When you run this script, the number format of "000" is set to the cells "M2:M" of "BDD" sheet.
If you want to set the number format to the "M2:M", please modify getRange("M2:M" + sheet.getLastRow()) to getRange("M2:M").
References:
getActiveSpreadsheet()
getSheetByName(name)

The easiest way to get a range on a named sheet is to include the sheet name in the range reference, like this:
function formattingGpeTrait() {
SpreadsheetApp.getActive().getRange('BDD!M3:M').setNumberFormat('000');
}

I think that you can't use the standard number formats as they all will only evaluate your value to a real number value where '003' in reality is equal to '3' from a numeric sense.
You have two real options which is to either store the value in a Text column as "003" or prepend the value with an apostrophe "'003" which is basically the same as storing it as Text but the column can remain numeric.
You can create a custom number format for a cell/column to also do this but I am not certain how to accomplish this programatically. Basically, this is still going to end up like the Text variations I mention above, only you have a named format you can call. The data will still be stored as Text.

Related

How to use custom function ExtractAllRegex() as an array formula? [Google Sheets]

I'm using #Wiktor Stribiżew 's custom function ExtractAllRegex(). The script extracts all occurrences of a Regex pattern. In the example, I extract all words in column A starting with "v_"
Here is a Google Sheet showing what I'm trying to do.
The original strings are stored in column A. The custom function/the matches are in column B.
Wictors function works great for single cells. It also works great when I manually drag the formula down the column.
Here's Wictor's original code:
function ExtractAllRegex(input, pattern,groupId,separator) {return Array.from(input.matchAll(new RegExp(pattern,'g')), x=>x[groupId]).join(separator);}
Description:
input - current cell value
pattern - regex pattern
groupId - Capturing group ID you want to extract
separator - text used to join the matched results.
The question is, how do I turn column B into a working array formula? Or, perhaps better, how do I modify Wictor's script so it accepts a range instead and auto-fills down column B?
I updated your script to:
function ExtractAllRegex(input, pattern,groupId,separator) {
return input.map ? input.map( inp => ExtractAllRegex(inp, pattern, groupId, separator)) :
Array.from(input.matchAll(new RegExp(pattern,'g')), x=>x[groupId]).join(separator);
}
and changed the formula in B2 to
=ExtractAllRegex(A2:A13,"(v_.+?\b)",0," ")
See if that works for you?

Using named ranged in google sheets as variables in custom formulas

Not sure if this is going to make sense but here I go.
What I want to do is to create a formula that isn't linked to a cell directly. In example: if I want to calculate carryweight for a tabletop game like D&D I would need the formula (strengthBonus x 5). For my current attempt I renamed the range (cell rather) strengthBonus to MOD_STR so when I put the formula =(multiply(MOD_STR,5) it works like a charm. Then I named that range "CARRYWEIGHT" and then use it elsewhere.
What I would like to be able to do is to make a new variable, similar to the way that "Define Named Range" does, but instead of relying on the variables being somewhere on the spreadsheet they would process from an internal formula. For example, if I type =carryweight into a cell it would run the equation =MULTIPLY(MOD_STR,5) in that cell and output the answer. I know nothing about code yet but have just been pointed in the direction of tutorials but I'm also asking for help here.
The code I have tried is
function CARRYWEIGHT(MOD_STR){
return MOD_STR*2}
and something else, I can't remember what but I got it to at least accept it in the spreadsheet. When I type it in I get an error stating that the outcome isn't a number.
I have no idea where to go from here.
Thank you in advanced for your help.
The difference between sheets formulas and Apps Script is that in Apps Script you need to retrieve the value of the range corresponding to the name of a named range
You cannot simply multiply the name of the range (which is a string!) with a number
Here is a sample of how to retrieve a range by name and make calculations wiht the value stored in it:
function CARRYWEIGHT(MOD_STR){
// retrieve all named ranges in the spreadsheet
var namedRanges = SpreadsheetApp.getActive().getNamedRanges();
//loop through all the results
for (var i = 0; i < namedRanges.length; i++){
var range = namedRanges[i];
//if the range with the name equal to the value of MOD_STR is found, get the cell content of this range
if(range.getName()==MOD_STR){
var value = range.getRange().getValue();
// perform the calculation with the cell content of the named range
return value*2;
}
}
}
From the cell, call the function as =CARRYWEIGHT("paste here the name of the range of interest"), do not forget the quotes (unless it is a cell reference)!
I hope this helped you to get started, for further understanding plese consult the following references.
References
Named Ranges
Loops
Conditional statements
Ranges
getValue()

How Do You Find The Last Row In A Range That Matches Certain Criteria? (Google Apps Script)

I have a parts database of over 150 rows of data each with individually unique part numbers with starting letters to indicate their system name (Part-12XX are for bolts or whatnot). Is there a function like textfinder or intuitive way to find the last result of this text range criteria so I could automatically add a part with the next sequential number.
Excel uses find directions or even xlUp to search from bottom up. I looked up the class TextFinder and that did not seem to work.
I'm using Google Apps Script.
// Creates a text finder for the range.
var textFinder = range.createTextFinder('Part-12');
// string to be replaced with right() command
You want to retrieve the row number of the last row when the value which has Part-12 as the prefix is found in the range of the Spreadsheet.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
Modification points:
In this answer, "TextFinder" is used.
useRegularExpression() is used. The official document is as follows.
configures the search to interpret the search string as a regular expression; otherwise the search interprets the search string as normal text.
findAll() returns all ranges of the search result as an array. In this case, the last element of the array is the value you want.
Sample script:
var textFinder = range.createTextFinder('^Part-12').useRegularExpression(true); // In this case, '^Part-12' is used at the regex.
var result = textFinder.findAll();
var row = result[result.length - 1].getRow();
Logger.log(row); // This is the last row number.
This script supposes that range is declared.
References:
useRegularExpression()
findAll()
If I misunderstood your question and this was not the result you want, I apologize.

How to create INDIRECT array string of multiple sheet references in Google Sheets?

I am attempting to use a query to display data off multiple Google Sheets. I make a new sheet every week that has a specific sheet name, e.g. Week of 01/13, Week of 01/06 and so forth.
The following is where my idea spawned from for reference:
I have a summary sheet that is using COUNTA(INDIRECT("'" & A5 &
"'!E4:E",true)
A5 being a cell that concatenates a date and words to replicate the
sheet names.
The row on the summary sheet does not populate until B5<=today()
So I am able to set it an forget it and the sheet will continue to
give me my weekly data as the days progress and keeps the sheets clean
until the week is upon us.
Long story short, I have a query that I use that gives me all the data I need with a specific parameter but I have to manually update the data syntax array with the new sheet names each week.
=QUERY({'Week of 01/13'!A:P;'Week of 01/06'!A:P;'Week of 12/30'!A:P;'Week of 12/23'!A:P;'WEEK OF 12/16'!A:P;'WEEK OF 12/09'!A:P;'WEEK OF 12/02'!A:P;'WEEK OF 11/25'!A:P;'WEEK OF 11/18'!A:P;'WEEK OF 11/11'!A:P;'WEEK OF 11/04'!A:P;'WEEK OF 10/28'!A:P;'WEEK OF 10/21'!A:P;'WEEK OF 10/14'!A:P;'WEEK OF 10/07'!A:P;'WEEK OF 09/30'!A:P;'WEEK OF 09/23'!A:P;'WEEK OF 09/16'!A:P;'WEEK OF 09/09'!A:P;'WEEK OF 09/02'!A:P},
"Select * where Col11 = 'RD' order by Col2 desc",0)
I would like to build a reference to an array that will auto-populate a concatenation based on the day.
Using the following code I can have the concatenate give me the array I need,
=if(H4<=today(),CONCATENATE("'",H$1,text(H4,"mm/dd"),"'!A:P;",),"")
but when I try to input it into the query function it just returns the concatenated text:
=QUERY(I1,"Select *")
'Week of 01/06'!A:P;'Week of 01/13'!A:P
I have tried with and without the curly brackets with no success.
I would like the sheet to be able to refresh and see that it is the correct day, the new sheet name is populated and the query gets updated.
I need help with making I1 work.
Link to Test Query Sheet
dudes who copy-pasted INDIRECT function into Google Sheets completely failed to understand the potential of it and therefore they made zero effort to improve upon it and cover the obvious logic which is crucial in this age of arrays.
in other words, INDIRECT can't intake more than one array:
=INDIRECT("Sheet1!A:B"; "Sheet2!A:B")
nor convert an arrayed string into active reference, which means that any attempt of concatenation is also futile:
=INDIRECT(MasterSheet!A1:A10)
————————————————————————————————————————————————————————————————————————————————————
=INDIRECT("{Sheet1!A:B; Sheet2!A:B}")
————————————————————————————————————————————————————————————————————————————————————
={INDIRECT("Sheet1!A:B"; "Sheet2!A:B")}
————————————————————————————————————————————————————————————————————————————————————
=INDIRECT("{INDIRECT("Sheet1!A:B"); INDIRECT("Sheet2!A:B")}")
the only possible way is to use INDIRECT for each end every range like:
={INDIRECT("Sheet1!A:B"); INDIRECT("Sheet2!A:B")}
which means that the best you can do is to pre-program your array like this if only part of the sheets/tabs is existant (let's have a scenario where only 2 sheets are created from a total of 4):
=QUERY(
{IFERROR(INDIRECT("Sheet1!A1:B5"), {"",""});
IFERROR(INDIRECT("Sheet2!A1:B5"), {"",""});
IFERROR(INDIRECT("Sheet3!A1:B5"), {"",""});
IFERROR(INDIRECT("Sheet4!A1:B5"), {"",""})},
"where Col1 is not null", 0)
so, even if sheet names are predictable (which not always are) to pre-program 100+ sheets like this would be painful (even if there are various sneaky ways how to write such formula under 30 seconds)
an alternative would be to use a script to convert string and inject it as the formula
A1 would be formula that treates a string that looks like real formula:
=ARRAYFORMULA("=QUERY({"&TEXTJOIN("; ", 1,
IF(A3:A<>"", "'Week of "&LEFT(A3:A, 5)&"'!A1:D5", ))&
"}, ""where Col1 is not null"", 1)")
further populating of A6:A will expand the string automatically
then this script will take the string from A1 cell and it will paste it as valid formula into C5 cell:
function onEdit() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Master Sheet');
var src = sheet.getRange("A1");
var str = src.getValue();
var cell = sheet.getRange("C5");
cell.setFormula(str);
}
of course, the script can be changed to onOpen trigger or with custom name triggered from the custom menu or via button (however it's not possible to use the custom function as formula directly)
If you're trying to update the data your query is looking at and you're feeding it a string, you need to put that string within the indirect() function. That will interpret your string as a data reference and point your query() in the right direction.
So for this you'd probably have
=QUERY(INDIRECT(I1),"Select *")

Google Script setValue results in [[value]]

I am trying to come up with a script that will simply capture the value of a cell and paste that value in another cell. The cell value it is capturing is a simple, unformatted cell containing the number 32. My code below works but the result is not 32 in the target cell. Instead, the result is [[32.0]]. Can someone help me understand what it is adding the brackets and the .0?
function test(row) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();// Define active sheet
var amountdue = sheet.getRange("A30").getValues();// Capture amount due
sheet.getRange("B30").setValue(amountdue);// Paste amount due
}
The function that you are using "getValues()" is intended to capture more than one cell. As this function is designed to capture a table it give in output a result that is not the value of one cell but the value of several cells. to display them we need to store them in something that it's easily accessible and structured : an array.
The array is represented as: [cell1Value, cell2Value, cell3Value, ...] .
As there may have more than one row we store each row in an other array: [row1, row2, row3, ...]. so in the end it's something like that:
[ [row1Cell1, row1Cell2, ...], [row2Cell1, row2Cell2, ...] ]
You don't want these brackets, change "getValues()" for "getValue()" without "s".
Or when you set the value use:
amoutdue[0][0]
the first [0] is to say I want the first row (we start at 0) and the second [0]... you already guessed is for the first cell.
I suppose that you are getting the ".0" after "32" because as you are trying to set the array of array in a cell. Javascript don't know how to handle that and try to transform the array of array in full text.