Using .indexOf() to define .getRange() - javascript

I am currently trying to use the .indexOf of a .getValues() array value, to define the cell I want a hyperlink copied in (as proof of concept).
Code looks as follows:
var descriptionColumn = headerArray[0].indexOf("Description")
sheet.getRange(sheet.getLastRow() + 1, descriptionColumn + 1).setFormula('=HYPERLINK("www.google.com"; "Test")')
Logger.log(descriptionColumn)
The headerArray is filled as follows:
var headerArray = sheet.getRange(1, 1, 1, lastColumn).getValues();
Now the log is showing me, that the descriptionColumn is being returned as "3.0". The position 3 is correct, yet I am unsure if the ".0" is messing with the next code. Because whenever I replace descriptionColumn in the .setFormula area, my code works. Any idea what I'm doing wrong and how to fix it? I am using .indexOf() in other places to refer to the index of another array without issue. Only here I don't get it to work..
EDIT: Reproducible Example and findings.
Thanks a lot for all your help so far, and sorry for coming back so late!!
I have in the meantime found out, that one of the issues was the "+ 1" after sheet.getLastRow() in
sheet.getRange(sheet.getLastRow() + 1, descriptionColumn + 1).setFormula('=HYPERLINK("www.google.com"; "Test")')
I honestly don't fully understand why this is the case yet, but by positioning this at the very end of my code (so that it is indeed the lastRow when inserted, I was able to fix this (saving it in a separate variable such as with "descriptionColumn" also didn't help..). I understood .getLastRow returns an Integer, so the + 1 operation in theory shouldn't be an issue, right? Happy to learn if I got something wrong.
So finally with below code I was able to insert the hyperlink as planned. Indeed starting with .setValue instead of .setFormula did help me a lot, so thanks!! :)
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var headerArray = sheet.getRange(1, 1, 1, lastColumn).getValues();
var projectRef = "TEST123"
var folderID = DriveApp.getFolderById("SOME FOLDERID").createFolder(projectRef).getId()
var descriptionColumn = parseInt(headerArray[0].indexOf("Description"))
sheet.getRange(sheet.getLastRow(), descriptionColumn + 1).setFormula('=HYPERLINK("https://drive.google.com/drive/folders/' + folderID + '"; "' + projectRef + '")')

yet I am unsure if the ".0" is messing with the next code
No, that's not a problem
Only here I don't get it to work
We can't see your error, or description what goes wrong.
--- Debug Steps: ---
Replace .setFormula with .setValue("Test") to see if you are targeting the right cell (column)
If that works, then the problem is in your formula

Related

Parse #Error When Adding Formula with Javascript

I am having a really weird phenomenon happen in Google Sheets, and I've found nothing on this issue in my research. I'm adding a query formula with javascript and getting a #Error on the sheet. After quadruple checking I wasn't messing up the formula string (the first and most obvious thing to cause such an error) and satisfying myself that the formula was correct for syntax, I cut the formula from the formula bar, hit enter to make the cell blank, then pasted the formula I just cut back in, and boom. Correct result, no error. No change to the formula whatsoever.
So is the a bug with the script editor/sheet interaction? Is a bug in Sheets? Am I doing something wrong (can't imagine what)?
I even followed another post's suggestion and replaced the comma argument separator with a semicolon, but no change in behavior. I have pasted the relevant code here, but I have also shared a Google sheet with the link below that demonstrates the issue.
To reproduce, follow these steps:
Go to the sheet via the link below.
Open Script Editor, and run the function "AddFormula"
When the script runs it will add the formula shown below and you will see a #Error (parse error).
Cut the formula from the formula bar on the sheet and press enter, creating the blank cell.
Copy the formula you just cut back into the cell. Here you will see the correct result of the formula displayed instead of the #Error.
For reference, the relevant code is here:
var wbID1 = "1tujKM_cAePTjBVS6q-gzGheSOAVz68vI0yi_LigCvyw";
var wb = SpreadsheetApp.openById(wbID1); //The entire workbook.
var wsT = SpreadsheetApp.openById(wbID1).getSheetByName("TData"); //T=Target Worksheet
function AddFormula() {
wsT.clear();
wsT.getRange(2,1).setValue("AL");
var TargetRange = wsT.getRange(2,1).getValue();
var QueryString = "=QUERY(States!A2:E; \"Select D where B = '" + TargetRange + "'\")";
wsT.getRange(2,3).setFormulaR1C1(QueryString);
}
The constructed formula in question resolves to:
=QUERY(States!A2:E, "Select D where B = 'AL'")
A demo sheet is here that reproduces the issue:
Demo Sheet
It would be great if there was a solution to this issue, but if that is too much to ask, I would love to simply be affirmed that I'm not crazy! Thanks all!
Use Range.setFormula(formula), since your formula uses an A1 notation States!A2:E
If you use Range.setFormulaR1C1(formula), the given formula must be in R1C1 notation.
Example: =SUM(R[-3]C[0]:R[-1]C[0])
Your Code:
function AddFormula() {
wsT.clear();
wsT.getRange(2,1).setValue("AL");
var TargetRange = wsT.getRange(2,1).getValue();
var QueryString = "=QUERY(States!A2:E; \"Select D where B = '" + TargetRange + "'\")";
wsT.getRange(2,3).setFormula(QueryString);
}
Output:

using a variable within a string with Google Sheets

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);

How to set formula by using google spreadsheets app script?

Actually, question is - how to recreate type of formulas:
ArrayFormula(replace(replace(regexreplace(K1:K&"","[-/,. ()]",""),4,0,"-"),8,0,"-"))
into code. Unfortunately, i didn't find it by myself, so I'm asking for help.
Upd.
Let me clarify just a little.
Part of code which was used by me into script:
value = value.replace(/^ /, '').replace(/[. )]/g, 'a').replace(/[+]/g, '').replace(/(aa)/g, '-').replace(/(a)/g, '-').replace(/[(]/g, '-');
value = value.replace(/^-/, '');
value = value.replace(/-$/, ''); range2.setValue(value);
This is example of a result:
"(22)road.CA" - "22-road-CA";
"22roadCA" - is not(eror).
If we working into google spreadsheets we could use formula's which I'm typed before, and in this case, results will be the:
"(22)road.CA" - "22-road-CA";
"22roadCA" - "22-road-CA".
So, how to create right code for it? Mb I should delete all signs, use looping method for check sign by sign, and insert my variant after some count of cell array?
Simple example :
var formulaTargetCell = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet()
.getRange(1, 1, 1, 1);
formulaTargetCell.setFormula('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))');
//or
var formulaTargetCell = SpreadsheetApp
.getActiveSpreadsheet()
.getActiveSheet()
.getRange('B2');
formulaTargetCell.setFormulaR1C1('=ArrayFormula(replace(replace(regexreplace(K1:K&"""",""[-/,. ()]"",""""),4,0,""-""),8,0,""-""))');
There are still some kind of way to set formula in app script that documented in available API of Range

JavaScript DOM Dependent on Viewport Causing Strange Results

I am trying to find occurrences of a string in another string that has been pulled from the HTML document. The page is an SNMP monitor but we have been having issues in the past with CTRL + F because it only wants to find the string within the current viewport of the browser. My attempt at getting around this and not having to look through things manually was to write a script.
The issue here is that it appears the docHTML variable is only able to hold so much data and anything else is truncated. I have looked around on Stack Overflow and found that my string size is significantly less than other people have tried, so that shouldn't be the issue.
All of the IP addresses in the 'ipArray' variable do exist on the page in different locations and are in the docHTML variable when I look through it myself. When I run the doSearch function at various points in the page (viewport dependent) it gives me different results.
I really don't know what has gone wrong here as the code does work sometimes, and not other times. My goal is to have the code go through the whole page and find all missing IP's and add them to the array so that we can go ahead and add them instead of having to compare 490 IP's on a spreadsheet to up to 490 in the monitoring utility.
Thanks in advance!
var docHTML = document.documentElement.outerHTML;
var missing = [];
function doSearch(text) {
if (docHTML.search(text) == -1){
missing.push(text);
}
}
var ipArray = [
"192.168.64.236",
"192.168.64.237",
"192.168.64.238",
"192.168.64.10",
"192.168.64.11",
"192.168.64.12",
"192.168.65.40",
"192.168.65.47"
];
var Total = ipArray.length;
for(i=0;i<Total;i++){
doSearch(ipArray[i]);
}
console.log("Missing IP's: " + (Total - missing.length));
console.log(missing);
Here is the solution, not much of change, just a tweak to your logging statement. You were printing "total-missing" which is wrong. What we need is the missing count-
var docHTML = document.documentElement.outerHTML;
var missing = [];
function doSearch(text) {
if (docHTML.search(text) == -1){
missing.push(text);
}
}
var ipArray = [
"69.171.224.11",
"199.59.149.230",
"174.121.194.34",
"209.200.154.225",
"69.174.244.50",
"67.201.54.151"
];
var Total = ipArray.length;
console.log(Total);
for(i=0;i<Total;i++){
doSearch(ipArray[i]);
}
console.log("Missing IP's: " + (missing.length)); /***HERE***/
console.log(missing);
Other than this, the whole code worked for me as expected. Let me know what else/exactly is the issue. Happy to help.
The code works as intended. The issue happened to be the SNMP monitor it is running on top of. Everything on the page seems to be loaded by POST requests as you scroll. It seems to grab a few before and after which was why I was able to see it in the code and not when executing.

Adding and Displaying Array Issue

var reset = function ()
{
var p = parseFloat($("#IA").val());
var q = parseFloat($("#IB").val());
var m = parseFloat($("#CGCD").val());
var aR = [];
aR += ["GCD(" + p + "," + q + ")=" + m];
document.getElementById("PGCD").innerHTML = aR + "\n";
document.getElementById("IA-error").innerHTML="";
document.getElementById("IB-error").innerHTML="";
$("#IA").focus();
};
The code above is only for a 'reset' function, a part of additional code (not present), the purpose which is to find the Greatest Common Denominator, GCD.
My 'reset' function is connected to a button, #reset, the purpose of which is to do four things:
add and store the string GCD(p,q)=m to the array 'aR'; p/q/m are variable stand-ins for the values of the input text areas #IA, #IB, and #CGCD (the GCD of #IA and #IB);
display the array 'aR' in a text-area #PGCD each time the reset button is clicked; this is why I used an array;
clear the two input text areas #IA and #IB;
clear the one output text area;
As it stands, all four objectives are completed successfully, with one exception: for the second objective, only the most recent GCD calculation is outputted; none of the previous calculations output.
I cannot get the array to list the different saved calculations within it. I think (?) the new calculations are being added to the array, but I am not sure.
I've tried a 'for' statement, and an 'if' statement, neither of which worked. I don't know whether I coded it wrong, or if it wasn't the right solution for my issue.
I tried to search the forums (here) for a solution, but was unable to find one.
Thank you.
If I'm understanding what you are describing, I believe your problem is that you are attempting to use += to add elements to an array. You should use
aR.push("GCD(" + p + "," + q + ")=" + m);
The += operator is used for addition of a value to itself as well as string concatenation.
Edit: per comments below, the main issue was declaration of aR as a local variable. It needs to be either global or declared within the same scope.

Categories