getSheetByName() returns null in google script - javascript

I am using the following code to try and set the sheet title to the name of the form that I have just connected to it with the code. However, I keep getting that the sheet name returning as "null", even though the debugger and physically looking at the sheet indicate that the name (Form Responses 1) is there. Any suggestions?
var data = SpreadsheetApp.create('C Term 2017 Unit 0');
var idlog = data.getId();
var title = 'RST.5';
for (i = 1; i <= 7; i++) {
var dataset = SpreadsheetApp.openById(idlog);
var sname = ('Form Responses ' + i);
var active = dataset.getSheetByName(sname);
active.setName(title);
}
Thank you!

Before
var sname = ('Form Responses ' + i);
add
var i = 1;

Maybe the variable i is not correctly converted to a string?
You could try converting i to string explicitly:
var sname = ('Form Responses ' + i.toString());

Related

Script to refresh data with IMPORTHTML in Google Sheets

I'm trying to get the data about XAU prices from table here: https://www.investing.com/currencies/xau-pln-historical-data
I need to have the data in google sheets and the problem is that it doesn't refresh the data. When I clean cells manually and insert formula then data is refreshed, but when I do it using script it doesn't work. I have this script (based on https://support.geckoboard.com/hc/en-us/articles/206260188-Use-Google-Sheets-ImportHTML-function-to-display-data-in-Geckoboard):
function getData2() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Rank");
var cellFunction = '=INDEX(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data","table",1),2,2)';
var PricesRange = sheetName.getRange('K2:K14');
PricesRange.clearContent();
var queryString = Math.random();
for (var j = 2; j <= 14; j++) {
var cellFunction2 = '=INDEX(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data","table",1),' + j + ',2)';
sheetName.getRange(j,11).setValue(cellFunction2);
}
}
I set up a trigger which runs the script every minute but the data is still the same.
Do you have any ideas what should I do?
A much easier solution is to enable circular references with 1 iteration. For example put in cell A1 =A1+1 then append your url with "?"&A1
You have declared the queryString variable but you have never used it. The idea of having it is to append it to the URL, so that it gets recognized as a different URL (that could yield different results). That causes the formula's results to be refreshed.
You can use the code below which uses the queryString variable:
function getData2() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Rank");
var PricesRange = sheetName.getRange('K2:K14');
PricesRange.clearContent();
var queryString = Math.random();
for (var j = 2; j <= 14; j++) {
var functionTemplate = '=INDEX(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data?%s","table",1),%s,2)';
var cellFunction2 = Utilities.format(functionTemplate, queryString, j);
sheetName.getRange(j,11).setValue(cellFunction2);
}
}
Additionally, you may be interested in replacing the for-loop for this single formula:
=QUERY(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data","table",1), "SELECT Col2 LIMIT 13 OFFSET 1", 0)
Which could be used in your code as follows:
function getData2() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Rank");
var PricesRange = sheetName.getRange('K2:K14');
PricesRange.clearContent();
var queryString = Math.random();
var functionTemplate = '=QUERY(IMPORTHTML("https://www.investing.com/currencies/xau-pln-historical-data?%s","table",1), "SELECT Col2 LIMIT 13 OFFSET 1", 0)';
var cellFunction2 = Utilities.format(functionTemplate, queryString);
sheetName.getRange(2, 11).setValue(cellFunction2);
}
You may also read more about the Utilities.formatString function in case you may need it here.

Can't get value from getSheetValues()

I'm having a bit of problem i can't solve, i'm just getting "undefined" with everything i try. What I do or I want to is compare some numbers from two sheets, if those sheet values match it should be: match! 131212 = 131212 and what i get is: match! undefined = undefined. I hope you could help me guys!
function najdiVprasanje()
{
var sheet = ss.getSheetByName("field_data_field_vprasanje");
var sheet_novo = ss.getSheetByName("novo");
var topRow = sheet.getLastRow();
var nid = sheet.getSheetValues(2, 4, topRow, 1);
var novo_nid = sheet_novo.getSheetValues(2, 1, topRow, 1);
for(var i=0;i<=topRow;i++)
{
for(var x=0;x<=topRow;x++)
{
if(novo_nid[i] == nid[x])
{
Logger.log("match found!" + novo_nid[i] + " == " + nid[x]);
}
}
}
I assume 'ss' represents the spreadsheet(workbook) ? It isn't defined anywhere. If your script is bound to a spreadsheet, your first line should probably look like
var ss = SpreadsheetApp.getActive();

Google Apps Script: Why are equal strings/values coming up as not equal

I have equal strings coming up as not equal in a google apps script function and can't figure out why. Other answers to this question on the forum are in other languages I don't understand yet. Here's the code:
function testForMatch() {
var ss = SpreadsheetApp.getActive();
var masterSheet = ss.getSheetByName('Leaderboard');
var masterLength = masterSheet.getMaxRows() - 3;
var masterData = masterSheet.getRange(4, 2, masterLength).getValues(); //gets all the student names from the leaderboard
var titleSheet = ss.getSheetByName('Title - Standard scores');
var titleLength = titleSheet.getMaxRows() -3;
var titleData = titleSheet.getRange(4, 2, titleLength).getValues(); //gets all the student names from the standard score sheet
for ( i = 0; i < masterLength; i ++) {
if(masterData[i] != titleData[i]) {
var row = i + 1;
var error = "Uh oh! It looks like " + masterData[i] + " and " + titleData[i] + " do not match in row " + row;
var ui = SpreadsheetApp.getUi();
var response = ui.alert(error);
}
}
}
even if I just type simple strings into the matching cells it tells me they don't match. Likewise for numbers.
Only thing I can think is that my script isn't actually comparing the values. If that's true, how do I get it to do that?
Thanks for helping!
if(masterData[i][0] != titleData[i][0]) {
...would compare the cell values

Apply for loop with variable

I am trying to condense my code because I have a lot of repetitive coding happening. I will need to apply this same example many times over. I want to create a for loop but my variable needs to increase as well. Right now I have my variable increasing but I am unable to implement my cell data into the variable. I think I am double assigning var h. I can't figure out how to get around this. Thank you for your help.
For Loop
for (var j = 2; j<15; j++){eval("var polebrea" +j);
var h = ("polebrea" +j)
}
h = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
Code Attempting To Implement
polebrea2 = document.getElementById("part1Table").rows[10].cells[2].innerHTML;
polebrea3 = document.getElementById("part1Table").rows[10].cells[3].innerHTML;
polebrea4 = document.getElementById("part1Table").rows[10].cells[4].innerHTML;
polebrea5 = document.getElementById("part1Table").rows[10].cells[5].innerHTML;
(cont. to 15)
Inserting Variable
<script>document.write(polebrea2)</script>
Ignoring design dogma....use the string index form of property access to set your variables:
// window is a bad place for this....you should probably put it on another object e.g. var polbreas = {};
for (var i = 2; i<15; i++){
window["polbrea"+i] = document.getElementById("part1Table").rows[10].cells[i].innerHTML;
}
While not necessarily good practice to do what you are doing, you could try this:
var createVariable = function( index ){
var variableName = "polebrea" + index;
var objName = document.getElementById("part1Table").rows[10].cells[index].innerHTML;
return (variableName + " = " + objName + ";");
};
for (var j = 2; j<15; j++){
var objToWrite = createVariable(j);
console.log( objToWrite );
}

Getting same result from function every time

why is my function returning the same result?
I would like to input all the values from the “ping” function to an array and then output that array in html.
I run the function 3 times but all three times the result is the same. Can you tell me why?
(The domains are just an example by the way, cant put originals here)
var str = ' ';
var t=[];
var n= 2;
var arr = ["www.google.com","www.example.com","www.example2.com"];
var results = [];
var finalurl = '';
function fun1(){
for (var i=0; i < arr.length; i++){
str = "http://" + arr[i] + "/images/";
finalurl = str + "image-l.gif" + "?id=" + (new Date()).getTime();
ping(finalurl);
textt += results[i] + " ";
$(‘#ping’).html(textt);
}
}
var ping = function(finalurl) {
var l = 0;
t.push((new Date()).getTime());
if(t.length > n) {
p=t[2]-t[1];
results.push(p);
}
else {
var img = new Image;
$(img).load(function() {
ping();
}).attr('src', finalurl);
}
}
//small part of html:
<h2>run</h2>
<h1 id=“ping”> </h1>
This generates three urls (the length of arr) but only attempts to show two (the value of n). The urls are different each time, but you are limiting them in ping so the new ones are not used.
Try setting n to higher number, you will see it will load more images each click - as it currently stands it tries to load more in a single click (3) than it allows (2).
Note: even if those urls are different, the images may be the same, this happens if the server ignores the id parameter... which probably does as it requires additional configuration for the server to handle requests to a ".gif" resource (which is not a known servcer side scripting language) - by default the server will just return the resource image-l.gif.
By the way: At $(‘#ping’) those are the wrong quotes. Also textt is not defined - I did define it as var textt = ''; for my tests.

Categories

Resources