This is becoming a little strange because I think it's something very simple and for some reason still giving unexpected results.
So basically I have an input field and I have a table.
The user can type in the input field and search within a specific column of the table.
So a typical cell might have a date, for example "24/03/2020".
Now if the user types in "24" using includes I get false.
This is a sample code:
let _t = $('input[data-search="date"]').val(); //gets the user input text
let _c = $(v).find('td[data-query="date"]').html(); //gets the cell data
var _r = (_t.toLowerCase().includes(_c.toLowerCase()))
Now when I output the result in the console console.log(_t, _c, _r), I get the following result if the user inputs '24' and there is a cell containing '24/03/2020'
24 – "24/03/2020" – false
This is very strange! Somebody please help!
includes searches for a substring inside a of a string. So you have to search 24 inside 24/03/2020, not 24/03/2020 inside 24.
So just use this line of code:
var _r = (_c.toLowerCase().includes(_t.toLowerCase()))
instead of:
var _r = (_t.toLowerCase().includes(_c.toLowerCase()))
I'm trying to come up with an IF statement that will trigger my macro to run based on a specific value in one cell. My Spreadsheet has many tabs. This is for a forecasting template.
Here is what I have come up with but I am running out of ideas..
function Sum_Calcs() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Integrity Check'), true);
spreadsheet.getRange(K20).getValue(getActiveRange(), true);
if(activeRange === "1") {
}
//My Script is then located beneath//
Any help is much appreciated!
You need to
implement an onEdit function to re-evaluate the if statement each time the value in "K20" was changed (please note that it will work automatically only if the value has been changed manually, by a human)
A second function (macro) that will be called within the if statement if your condition is fulfilled
Based on your code snippet above there some things you need to change:
When you use the method getValue() to retrieve the value of a cell - do not specify any parameter within the brackets () of the method. Instead, assign the return value of this method to a variable
If you want to retrieve a cell value (or perform any other operation) in a certain sheet, use getSheetByName() instead of setActiveSheet
To compare within an if statement the actual value against an integer (number) use if(activeRange == 1)
Note that when getting a range in A1 notation you need to use quotes ("")
Sample code based on your situation:
function myForecastMacro(){
// specify here what shall happen if your "if" statement is fulfilled
function onEdit() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('Integrity Check');
var activeRange=sheet.getRange("K20").getValue();
if(activeRange == 1) {
myForecastMacro();
}
}
I have a WooCommerce store, which is connected with Zapier to a Google spreadsheet. In this file, I keep track of the sales etc. Some of these columns contain -obviously- prices, such as price ex VAT, etc. However, for some reason the pricing values are stored in my spreadsheet as strings, such as 18.21.
To be able to automatically calculate with these values, I need to convert values in these specific columns to numbers with a comma as divider. I'm new to Google Script, but with reading some other post etc, I managed to "write" the following script, which almost does the job:
function stringIntoNumber() {
var sheetActive = SpreadsheetApp.openById("SOME_ID");
var sheet = sheetActive.getSheetByName("SOME_SHEETNAME");
var range = sheet.getRange("R2:R");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(".", ",")];
}));
}
The script works fine as long as only values with a dot can be found in column R. When values that belong to the range are changed to values with a comma, the script gives the error:
TypeError, can't find the function Replace.
Select the column you want to change.
Goto Edit>Find and Replace
In Find area put "."
in Replace with area put ","
The error occurs because .replace is a string method and can't be applied to numbers. A simple workaround would be to ensure the argument is always a string, there is a .toString() method for that.
in your code try
return [row[0].toString().replace(".", ",")];
The locale of your spreadsheet is set to a country that uses commas to seperate decimal places. Zapier however seems to use dots and therefore google sheets interprets the data it gets from Zapier as strings since it can't interpret it as valid numbers.
If you change the locale to United States (under File/Spreadsheet settings) it should work correctly. But you may not want to do that because it can cause other issues.
You got a TypeError because the type was number and not string. You can use an if statement to check the type before calling replace. Also you should convert the type to 'number' to make sure it will work correctly independent of your locale setting.
range.setValues(range.getValues().map(function(row) {
if(typeof row[0] === "string") return [Number(row[0].replace(",", "."))];
else return row;
}));
In this case I convert , to . instead of the other way around since the conversion to number requires a ..
Click on Tools > Script Editor.
Put this on your macros.gs (create one if you don't have any):
/** #OnlyCurrentDoc */
function ReplaceCommaToDot() {
var range = SpreadsheetApp.getActiveRange();
var col = range.getColumn();
var row = range.getRow();
function format(str) {
if(str.length == 0) return str;
return str.match(/[0-9.,]+/)[0]
.replace('.','')
.replace(',','.');
}
var log = [range.getRow(), range.getColumn()];
Logger.log(log);
var values = range.getValues()
for(var row = 0; row < range.getNumRows(); row++){
for(var col = 0; col < range.getNumColumns(); col++){
values[row][col] = format(values[row][col]);
}
}
range.setValues(values);
}
Save. Go back to the spreadsheet, import this macro.
Once the macro is imported, just select the desired range, click on Tools > Macro and select ReplaceCommaToDot
Note: This script removes the original ., and replaces , by .. Ideal if you are converting from US$ 9.999,99 to 9999.99. Comma , and whatever other text, like the currency symbol US$, were removed since Google Spreadsheet handles it with text formatting. Alternatively one could swap . and ,, like from US$ 9.999,99 to 9,999.99 by using the following code snippet instead:
return str.match(/[0-9.,]+/)[0]
.replace('.','_')
.replace(',','.')
.replace('_',',');
An alternative way to replace . with , is to use regex functions and conversion functions in the Sheets cells. Suppose your number is in A1 cell, you can write this function in any new cell:
= IF(REGEXMATCH(TO_TEXT(A1), "."), VALUE(REGEXREPLACE(TO_TEXT(A1), ".", ",")), VALUE(A1))
These functions do the following step:
Convert the number in the target cell to text. This should be done because REGEXMATCH expects a text as its argument.
Check if there is a . in the target cell.
If there is a ., replace it with ,, and then convert the result to a number.
If there is no ., keep the text in the target cell as is, but convert it to a number.
(Note : the Google Sheets locale setting I used in applying these functions is United States)
I have different solution.
In my case, I`m getting values from Google Forms and there it is allowed use only numbers with dot as I know. In this case when I capture data from Form and trigger script which is triggered when the form is submited. Than data is placed in specific sheet in a specific cell, but formula in sheet is not calculating, because with my locale settings calculating is possible only with a comma not dot, that is coming from Google Form.
Then I use Number() to convert it to a number even if it is already set as a number in Google Forms. In this case, Google Sheets script is converting number one more time to number, but changes dot to comma because it is checking my locale.
var size = Number(sizeValueFromForm);
I have not tested this with different locale, so I can`t guarantee that will work for locale where situation is opposite to mine.
I hope this helps someone. I was looking for solution here, but remembered that some time ago I had similar problem, and tried this time too and it works.
=IF(REGEXMATCH(TO_TEXT(F24);"[.]");REGEXREPLACE(F24;"[.]";",");VALUE(F24))
Works for me
If find dot replace with comma if not, put value
I am using Google Apps for Sheets. I am trying to use a defined variable within a string. I know the variable (lastRow) is the number I want (that number being "11") as I can see it in the logs. I have tried different ways of combining the letter "C" with the variable, but nothing works! I know it works as it is used in the "copyValuesToRange" method. Am I trying to do something that cannot be done, or is there a way to add the variable to the A1 notation so that the range will be read as C1:C11? Thanks from a relatively novice newbie!
var lastRow = sheet.getLastRow();
Logger.log(sheet.getLastRow());
// Inserts 1 column after column A=1 (Seq)
sheet.insertColumnsAfter(1,1);
// New column(s) due to added column(s)
var range = sheet.getRange("C1:ClastRow");
//Copied to Col A=1
range.copyValuesToRange(sheet,1,1,1,lastRow);
While writing this, the "Similar Question" box showed a link to "Google script string with a variable". I looked at that, but did not understand it "(!
You dont do it like that, you need to know concatenation.
var lastRow = 11;
console.log("C"+lastRow);
will output:
C11
which is what you're going for.
var range = sheet.getRange("C1:C"+lastRow);
So don't crucify me too badly if this is a dumb question,
But I've been dabbling in Google App Scripts, mainly its uses within Google sheets.
Generally when I've been using openById()
If it's an ID that might change regularly, I'll put it at the top of my script and add notes on how to edit (for the user i hand sheet over to, or for me as a reminder if i've not worked on it for a bit and i forget). If's pretty stangnant and not likely to change, I'll just declare it as a var.
I was thinking it's a bit more user friendly to have a "settings" sheet within the spreadsheet and the user inputs the settings. Rather than having to go into script editor to edit things.
But even via sheet, or script editor, a single thing added or removed in the wrong place can cause havock, like a space or /
At least with a "settings" sheet, you can use data validation and regular expressions to control and reject what the user inputs.
So I guess my question is Google Sheets ID's seem alien to me, bar length, and I was wondering is there any way to validate the ID's using regular expressions or something, rather than checking the ID server side.
Thanks :)
You can also use openByUrl() in your scripts, so users can just paste a link.
but if you must validate the ID:
ss = SpreadsheetApp.getActiveSpreadsheet();
function validate(){
//"sheetRef" is the name of the cell where you enter the id
//this function takes the string value of "sheetRef"
//and replaces it with the validation result.
var sheetRefCell = ss.getRangeByName("sheetRef");
var sheetRefString = sheetRefCell.getValue();
var validationResult = '{' + sheetRefString + '}';
try {
validationResult = validationResult +
' \n $ references: \n [' +
SpreadsheetApp.openById(sheetRefString).getName() +
']';
}
catch (e) {
validationResult = validationResult +
' \n $ is an invalid reference: \n [' +
e +
']';
}
finally {
sheetRefCell.setValue(validationResult);
}
}
when you run this it will replace the value entered in your 'sheetRef' (ID) cell with the validation result message. I recommend that you also add a time-based trigger to contininuously revalidate your ID.
Then you can add another cell to your spreadsheet which will extract the validated ID from 'sheetRef'. This cell should contain the formula:
= IF (IFERROR( SEARCH( 'invalid' , sheetRef ), 0 ) > 0,
"Invalid",
IFERROR( REGEXEXTRACT( sheetRef,"{(.*?)}" ), "Undetermined" )
)
So the cell with the above formula will EITHER display a valid id or "Invalid"/"Undetermined".