Can't get value from getSheetValues() - javascript

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

Related

Pulling data from an API using Google App Script

I'm hoping someone could help as I've spent the last day trying to figure out where I'm going wrong.. to no avail.
I'm trying to pull some basic information from https://nvd.nist.gov/ using their API (https://services.nvd.nist.gov/rest/json/cve/1.0/cve-id). I need to pull the data for cve-id's. cve-id's are in column A.
Example cve-id: https://services.nvd.nist.gov/rest/json/cve/1.0/CVE-2019-9763
The only information I want is the description, cvssV3baseScore, cvss3vectorString. Very basic you might think but I'm lost after doing tons of research.
I've tried doing this using the following code in Google Apps Script:
function fetchData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("CVEs");
var sheetData = sheet.getDataRange().getValues();
var i, len = sheetData.length, row = [];
for (i = 1; i < len; i++) {
if (sheetData[i][0] == "" || sheetData[i][15] != "")
continue;
// sheetData[i][8] - here 8 represents column I as column A = 0. Column 23 = x, this is where sheet ends (at new Date())
let url = 'https://services.nvd.nist.gov/rest/json/cve/1.0/' + sheetData[i][0];
try {
var id = json.result.CVE_items.cve.CVE_data_meta.ID;
var idStr = '';
var response = UrlFetchApp.fetch(url).getContentText();
row.push([
idStr,
json.result.CVE_items.cve.CVE_data_meta.ID,
json.result.CVE_items.cve.description.description_data.value,
json.result.CVE_Items.impact.baseMetricV3.cvssV3.vectorString,
json.result.CVE_Items.impact.baseMetricV3.cvssV3.baseScore,
]);
//Here (middle number) 10 number denotes the exact column number from where we need to write data. 10 = J
sheet.getRange(i + 1, 2, 1, row[0].length).setValues(row);
}
catch (e) {
continue;
}
}
}
function lookupByNthValue(search_key, sourceColumn, targetColumn, n) {
if(arguments.length < 4){
throw new Error( "Only " + arguments.length + " arguments provided. Requires 4." );
}
var count = 1;
for(var i = 0; i < sourceColumn.length; i++){
if(sourceColumn[i] != search_key){
continue;
}
if(count == n){
return targetColumn[i];
}
count++;
}
}
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Actions")
.addItem("Fetch Data", 'fetchData')
.addToUi();
}
I would much appreciate if someone could help, link to the Google sheet: https://docs.google.com/spreadsheets/d/18ilCE1udUM87c4YtxXAB52Fm3mEzDk8UggcH96S3JLA/edit?usp=sharing
Thank you in advance.
There are a few problems: len equals 1000 because you have data on row 1000! therefore the script will be too long. You write CVE_items instead of CVE_Items with a capital letter! CVE_Items is not a parent, it is an array, even with a single occurrence. You never parse the response of url fetch. Try this
function fetchData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("CVEs");
var sheetData = sheet.getDataRange().getValues();
var i, len = sheet.getLastRow(), row = [];
Logger.log(len)
for (i = 1; i < len; i++) {
try{
let url = 'https://services.nvd.nist.gov/rest/json/cve/1.0/' + sheetData[i][0];
var json = JSON.parse(UrlFetchApp.fetch(url).getContentText())
var row=[]
row.push([
json.result.CVE_Items[0].cve.CVE_data_meta.ID,
json.result.CVE_Items[0].cve.CVE_data_meta.ID,
json.result.CVE_Items[0].cve.description.description_data.value,
json.result.CVE_Items[0].impact.baseMetricV3.cvssV3.vectorString,
json.result.CVE_Items[0].impact.baseMetricV3.cvssV3.baseScore,
]);
Logger.log(row)
sheet.getRange(i + 1, 2, 1, row[0].length).setValues(row);
}catch(e){}
}
}

Trying to paste Values from formula Google App Script

This is just a snippet of my code from Google App Script which iterates through each row in columns 1, 2, 3. If an edit is made in column 3, an incremental ID will be generated and a concatenation of the same row and different columns will also be generated - in this case Column D, E, and F. I am struggling with figuring out a way to change the formulas into values. What am I missing here?
// Location format = [sheet, ID Column, ID Column Row Start, Edit Column]
var locations = [
["Consolidated Media Plan",1,9,3]
];
function onEdit(e){
// Set a comment on the edited cell to indicate when it was changed.
//Entry data
var range = e.range;
var col = range.getColumn();
var row = range.getRow();
// Location Data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
function getNewID(){
function IDrange(){
var dataRange = sheet.getDataRange();
var lastRow = dataRange.getLastRow();
return sheet.getRange(IDrowStart,IDcol,lastRow-IDrowStart).getValues();
};
//Get largest Value in range
function getLastID(range){
var sorted = range.sort();
var lastIDval = sorted[sorted.length-1][0];
return lastIDval;
};
//Stores leading letters and zeroes and trailing letters
function getLettersNzeroes(id){
//Get any letters or zeroes.
var re = new RegExp("^([a-zA-Z0])$");
var letterZero = [];
for(char = 0; char < id.length; char++){
if(re.test(id[char])){
letterZero.push([char,id[char]]);// [[position, letter or zero]]
};
};
// Categorize letters and zeroes into start and end blocks
var startLetterZero = "",
endLetter = "",
len = letterZero.length - 1;
for(j = 0; j < letterZero.length; j++){
if(letterZero[j][0] === j){
startLetterZero += letterZero[j][1];
}else if(letterZero[j][1] !== "0" && letterZero[len][0] - (len - j) == letterZero[j][0]){
endLetter += letterZero[j][1];
};
};
var startNend = {"start":startLetterZero,"end":endLetter};
return startNend;
};
//Gets last id number. Adds 1 an checks to set if its new length is greater than the lastNumber.
function getNewNumber(id){
var removeZero = false;
var lastNum = parseInt(id.replace(/\D/g,''),10);//Remove letters
var newNum = (lastNum+1).toString();
if(lastNum.toString().length !== newNum.length){
var removeZero = true;
};
var newNumSet = {"num":newNum, "removeZero": removeZero};
return newNumSet
};
var lastID = getLastID(IDrange());
var lettersNzeroes = getLettersNzeroes(lastID);
var newNumber = getNewNumber(lastID);
//If the number is 9,99,999,9999 etc we need to remove a zero if it exists.
if(newNumber.removeZero === true && lettersNzeroes.start.indexOf("0") !== -1.0){
lettersNzeroes.start = lettersNzeroes.start.slice(0,-1);
};
//Rejoin everything together
var newID = lettersNzeroes.start +
newNumber.num +
lettersNzeroes.end;
return newID;
};
for(i = 0; i < locations.length; i++){
var sheetID = locations[i][0],
IDcol = locations[i][1],
IDrowStart = locations[i][2],
EditCol = locations[i][3];
var offset = IDcol - EditCol;
var cell = sheet.getActiveCell();
if(sheetID === sheet.getName()){
if(EditCol === col){
//ID Already Exists the editing cell isn't blank.
if(cell.offset(0,offset).isBlank() && cell.isBlank() === false){
var newID = getNewID();
cell.offset(0,offset).setValue(newID);
cell.offset(0,-1).setFormulaR1C1('=concatenate(R[0]C[-1],"_",INDEX(Glossary!K:K,MATCH(R[0]C[2],Glossary!J:J,0)))');
};
};
};
};
};
EDIT:
This is my full code, I have been unsuccessful with trying to retrieve just the values of the formula within the same (i.e, If C9 gets edited, a formula with the values specific to the 9th row should be populated)
Also, I've tried to add an index/match formula to the concatenation formula at the bottom of the code - it works as expected on the google sheets, but when I run it with the script it pastes the correct formula but it returns a #NAME? error message. However, when I copy and paste the exact same formula in the cell, it works perfectly, any idea what could be causing this error?
This works for me. I know it's not exactly the same thing but I didn't have access to getNewId()
function onEdit(e) {
var sh=e.range.getSheet();
if(sh.getName()!='Sheet1')return;
//e.source.toast('flag1');
if(e.range.columnStart==3 && e.range.offset(0,1).isBlank() && e.value) {
//e.source.toast('flag2');
e.range.offset(0,1).setValue(e.value);
e.range.offset(0,2).setFormulaR1C1('=concatenate(R[0]C[-1],"_",R[0]C[-2],"_",R[0]C[-3],"_",R[0]C[-4])');
}
}

Why is the comparison operator not finding matches in Google App Script?

I have a small function that takes a string (strOrder = 658492-1), splits it into just the first part before the '-' and compares it to values in a cell in a spreadsheet (which is also split). If it is a match, it should add the spreadsheet row to an array. Unfortunately, it is not finding any matches, but even the log shows they are the same. Help!
function getLinks2(strOrder) {
var mLinks = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Main');
var data = mLinks.getDataRange().getValues();
var boxOrder = '';
var shortOrder = '';
var sOrder = '';
var arrLinks = [];
data.shift();
strOrder = strOrder.replace(/\s/g, "");
var oTemp = strOrder.split('-');
boxOrder = oTemp[0];
Logger.log('boxOrder:x' + boxOrder + 'x');
for (var i = 0; i < data.length; i++) {
shortOrder = data[i][4].toString();
shortOrder = shortOrder.replace(/\s/g, "");
var soTemp = shortOrder.split('-');
sOrder = soTemp[0];
Logger.log('sOrder:x' + sOrder + 'x');
if (boxOrder == sOrder) {
Logger.log('match');
arrLinks.push(data[i]);
//the item matches the order id
} else {
//item does not match the order id
} // end if order id matches
} // end for loop through data
return arrLinks;
} // end function getLinks2
Here are the Log results:
boxOrder:x685492x
sOrder:x658492x
sOrder:x658492x
sOrder:x658492x
sOrder:x699249x
sOrder:x698406x
(I used the 'x' around the strings to check if there were extra spaces.)
What am I missing?
Thanks for any help!

getSheetByName() returns null in google script

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

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

Categories

Resources