how to place =importxml result to a google script array? - arrays

Could any one show me how i can add result of =importxml into an array inside google script. For example this the request inside google script :
=IMPORTXML("https://www.google.com/search?q=bmw&safe=off&tbs=qdr:d","//h3[#class='r']")
I want later iterate the array to look for specific String!

One option you can try is:
/* CODE FOR DEMONSTRATION PURPOSES */
function ImportXML2Array() {
var sheet = SpreadsheetApp.getActiveSheet(),
range,
values_array;
sheet.getRange("A1").setFormula('=IMPORTXML("https://www.google.com/search?q=bmw&safe=off&tbs=qdr:d"; "//h3[#class=\'r\']")');
range = sheet.getDataRange();
values_array = range.getValues();
range.clear();
Logger.log(values_array);
}
/* CODE FOR DEMONSTRATION PURPOSES */

Related

Apps Script (Google Sheets) How to perform .setHiddenValues with an Array

I have some values stored in an Array and now I want to remove ALL the values stored in this array from a filter.
The values are stored correctly in the array but I don't manage to remove the values from the filter.
The Array's name is HideValues
Here is some code:
var p = 0;
spreadsheet.getSheetByName('TEM Tool Data').getRange('\'TEM Tool Data\'!E1').activate();
var criteria = SpreadsheetApp.newFilterCriteria();
//Remove all PID´s from the filter
while (p < HideValues.length){
criteria.setHiddenValues([HideValues[p]]).build();
p++;}
//Filter
spreadsheet.getSheetByName('TEM Tool Data').getFilter().setColumnFilterCriteria(5, criteria);
//Copy filtered area
spreadsheet.getRange('A2:I1386').activate();
//Paste
spreadsheet.getSheetByName('Visualization').getRange('A5').activate();
spreadsheet.getRange('\'TEM Tool Data\'!A2:I1386').copyTo(SpreadsheetApp.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
spreadsheet.getSheetByName('Visualization').getRange('J3').activate();
};
You don't need to loop through the array
If your array is something like var HideValues = [1,2,3,4,5];,
you can simply specify criteria.setHiddenValues(HideValues).build(); - without the while loop
Also:
To a filter, you should create it first (if not already done) and apply it to a range, not sheet:
var filter = spreadsheet.getSheetByName('TEM Tool Data').getDataRange().createFilter();
filter.setColumnFilterCriteria(3, criteria);
You should apply it to a range, not a sheet

Return next element from an array in googlesheets using scripts

I have a list of names in a google sheet. I'm trying to create a function in google apps scripts that outputs the next name in the list to a different cell in the spreadsheet. Once I've returned each name, I want to go back to the beginning.
I've tried to use a for loop as well, but then the script just loops through every item, and I end up with the just the last item being returned.
function returnNextName() {
var nameList =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My
Homeroom").getRange(2, 1, 22).getValues();
var outputCell =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My
Homeroom").getRange(1, 4);
var i = 0;
i = i + 1;
i = i%nameList.length;
var nextName = outputCell.setValue(nameList[i]);
}
My goal is that every time I run the function, I will get the next name in the list. However, I only ever get the first name.
Every time you call the script you redefine
var i = 0;
i = i + 1;
i = i%nameList.length;
So your element nameList[i] will be always the same.
To avoid this, you need to use PropertiesService, as suggested by TheMaster.
ScriptProperties allows you to store the last index in the script properties and retrieve and modify it every time you use the script.
Sample:
if(PropertiesService.getScriptProperties().getKeys().length==0){ // first time you run the script
PropertiesService.getScriptProperties().setProperty('i', 0);
}
var i = Number(PropertiesService.getScriptProperties().getProperty('i'))%nameList.length;
outputCell.setValue(nameList[i][0]);
i++;
PropertiesService.getScriptProperties().setProperty('i', i);

Google Script: getValues() and setValues() for rectangular grid

In Google Sheets, when I store a given a1notation into an appendRow, I want the values from this appended Row to be shown on another sheet while retaining the grid structure it had when it was saved intitially.
So from the below code, the data from the appendedRow(11,5,1,5) shall be set to the grid I5:J7.
Sadly I am not proficient enough to work with for loops and push() / array, so I would appreciate your support greatly.
Thank you.
function Test() {
var rs = SpreadsheetApp.getActiveSpreadsheet();
var ss = rs.getSheetByName("Sheet");
var tempArray = [ss.getRange(11,5,1,5)]
var values = tempArray.getValues();
ss.getRange('I5:J7').setValues(values);
}
Google Apps Script documentation has a Reference section which gives you a brief explanation and example of different methods. Under
https://developers.google.com/apps-script/reference/spreadsheet/range#setvaluesvalues
you can see that the method setValues(values) requires the dimension of the origin and destination range to match. Thus, you cannot paste a 1x5 range into a 2x3 range.
What you can do is to loop through the cells of the destination range and to assign them sequentially a value from the origin range - until either all the values have been passed or the destination range is full. You could implement it like this:
function Test() {
var rs = SpreadsheetApp.getActiveSpreadsheet();
var ss = rs.getSheetByName("Sheet");
var values = ss.getRange(11,5,1,5).getValues();
var destination=ss.getRange('I5:J7');
var value=0;
for(i=1;i<=3;i++)
{
for(j=1;j<=2;j++)
{
var cell=destination.getCell(i,j);
if(typeof values[0][value] !== "undefined")
{
cell.setValue(values[0][value]);
}
value=value+1;
}
}
}

How to build multi-dimensional arrays in the appropriate orientation. (Rows/Cols in correct places)

I'm working on building a Google Sheets-based tool to calculate the cost of making various machined and fabricated parts. As it currently sits, there are about 60 different variables that I modify each time I build an estimate. Things like "number of parts," "length of bar to cut each part from," "cost/bar," "machining time," "machining rate," etc. All of these values I have populated on one sheet, and laid out in a way like. I want to make a button that takes a "snapshot" of all of these values, and stores them on another sheet for later reference. I'd then, ideally create another button, that allows me to re-populate all of the cells based off of a unique ID (such as Part #). This would let me tweak an estimate, or even refer back to material sizes etc in a meaningful way.
So far, I've created a "Named Range" for each of the values, so that as I change the layout, or add values, my script code should update accordingly, instead of using direct cell references.
I've built a few functions to get and set the value's of these named ranges. They're working as expected(i think) for what I'm trying to do. But when I try to place the array of Named Ranges inside of a multi-dimensional array of the named ranges WITH their respective values, I'm running into an issue where each named range is a ROW and their respective value is a second Column. And I need it swapped
I'm not super comfortable with multi-dimensional arrays and am thinking myself in circles trying to figure out how to transpose this logically. My gut says the way I'm attempting to build the arrays is my problem, not just how I'm iterating through them.
function saveCurrentValues(){
//set master spreadhseet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//set calc and save sheets to vars
var calcSheet = ss.getSheetByName('Part Cost Calculator')
var saveSheet = ss.getSheetByName('Saved Parts');
//set named ranges from calcSheet to array
var namedRanges = calcSheet.getNamedRanges();
var savedValues = new Array();
//find next available row for save data (currently troubleshooting)
var nextAvailSaveRange = saveSheet.getRange(1, 1, 60, 2);
//iterate through array and call getNamedRange() function to return name and current value
for(i = 0; i < namedRanges.length; i++){
savedValues[i] = getNamedRange(namedRanges[i].getName());
}
nextAvailSaveRange.setValues(savedValues);
}
function getNamedRange(name){
var ss = SpreadsheetApp.getActiveSheet();
var value = ss.getRange(name).getValue();
Logger.log([name,value]);
return [name, value];
}
As you can see by how I had to temporarily format the nextAvailSaveRange, it needs 60 ROWS, and only two columns, because of how the array is constructed. I'd like to better understand how I'm creating this multi-dimensional array vertically instead of horizontally, and how to fix it!
Once this is done, I'd like to create headers that match the Named Ranges on my save sheet, to allow me to iterate through functions and look for a match to the appropriate column by name. That way if I add more values or change their order, or the order of the array, it wont matter. I think I'll be able to figure that out pretty easily if I can control these damn arrays better!
I agree with the OP. Array building AND iteration are the immediate problems and they are the stumbling block to the development of the spreadsheet.
The OP has a raised number of issues, however the most immediate, and the one to be resolved under this answer, is the copying of a list of parts from one sheet to another. In the OP's code, named ranges were retrieved and used as a basis for creating the copy of the list of parts. However, this also creates a duplicate set of named ranges on the target sheet. In my view this was unnecessarily complicating the duplication of the parts list since it is easy to programmatically create/update a list of named ranges.
The following code consists of three functions:
so_5466573501() - Copies the list of parts from one sheet to another.
Named Ranges are ignored; the OP's stumbling block is the iteration of the raw data and management of arrays. This code deals only with that aspect as a means of simplifying this issue.
createnamedranges() - Programmatically creates/updates Named ranges.
This code is included to assure the OP that it is not important to make named ranges the focus of the duplication by showing how easy it is to programmatically turn a list of parts into a series of Named Ranges (for development, I created 60 Parts and the entire code executes in under a 1 second). The code assumes a list in two columns (Column A = Parameter Name, Column B = Parameter value). The code loops through the list creating/updating a set of named ranges - the range name is the Parameter Name in Column A, and the range itself is the the corresponding row in Column B. The name of the sheet is set in a variable, so this function can be easily adapted.
deletenamedranges() - Programmatically deletes Named ranges.
This code deletes all the Named Ranges from a given sheet. This function is included because the OP's existing code creates duplicate named ranges, and it might be necessary to quickly delete them from a sheet. The sheet name is stored as a variable, so the function can be easily adapted.
function so_5466573501() {
//set master spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//create variables for calc and save sheets
var calcSheet = ss.getSheetByName('Part Cost Calculator')
var saveSheet = ss.getSheetByName('Saved Parts');
//get the Parts Parameters from Part Cost Calculator
//var namedRanges = calcSheet.getNamedRanges();
//Logger.log("DEBUG: Number of named ranges on Parts Cost Calculator = "+namedRanges.length);
// get the number of parts in the list on Parts Cost Calculator
var Avals = calcSheet.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
//Logger.log("DEBUG: Number of parts in the list: "+Alast); //DEBUG
// get the parts list
var partsRange = calcSheet.getRange(1, 1, Alast, 2);
var partsRangeValues = partsRange.getValues();
//Logger.log("DEBUG: The parts range is: "+partsRange.getA1Notation());//DEBUG
//Logger.log("DEBUG: Parts List Row #1: Name: "+partsRangeValues[0][0]+", Value: "+partsRangeValues[0][1]);//DEBUG
// create an array to use for saving results and updating new Saved Parts sheet
var savedValues = new Array();
// Loop through the Parts List, row by row
for (i = 0; i < Alast; i++) {
// push the part name and part value onto the array
savedValues.push([partsRangeValues[i][0], partsRangeValues[i][1]]);
//Logger.log("DEBUG: Parts List: i = "+i+", Name: "+partsRangeValues[i][0]+", Value: "+partsRangeValues[i][1]);//DEBUG
}
// identify the range on the Saved Parts sheet to copy the parts list array.
var saveRange = saveSheet.getRange(1, 1, Alast, 2);
saveRange.setValues(savedValues);
}
function createnamedranges() {
//set master spreadhseet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//create variables for calc and save sheets
var calcSheetName = "Part Cost Calculator";
var calcSheet = ss.getSheetByName(calcSheetName);
// get the number of parts in the list on Parts Cost Calculator
var AVals = calcSheet.getRange("A1:A").getValues();
var ALast = AVals.filter(String).length;
// get the parts range and values
var partsRange = calcSheet.getRange(1, 1, ALast, 2);
//Logger.log("DEBUG: The Parts range is "+partsRange.getA1Notation());//DEBUG
var partsRangeValues = partsRange.getValues();
// Loop through the parts list row by row
for (var i = 0; i < ALast; i++) {
// get the Part name and assign as the range name
var nrpartname = partsRangeValues[i][0];
//Logger.log("DEBUG: PartName = "+nrpartname+", value: "+partsRangeValues[i][1]);//DEBUG
// get the range to be named -note (i+1) because the loop starts at 0 (zero) but `getrange` starts at 1 (one)
var rng_to_name = ss.getSheetByName(calcSheetName).getRange((i + 1), 2);
//Logger.log("DEBUG: rng_to_name: "+rng_to_name+", range details: "+rng_to_name.getA1Notation());
// set (and/or update) the named range
ss.setNamedRange(nrpartname, rng_to_name);
// DEBUG: check that the range was created //DEBUG
// var rangeCheck = ss.getRangeByName(nrpartname);//DEBUG
// var rangeCheckName = rangeCheck.getA1Notation(); //DEBUG
// Logger.log("DEBUG: Rangename: "+nrpartname+", Range: "+rangeCheckName);//DEBUG
// credit megabyte1024 https://stackoverflow.com/a/12325103/1330560 "setNamedRange() outside of the spreadsheet container?"
}
}
function deletenamedranges() {
//set master spreadhseet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//create variables for calc and save sheets
var calcSheet = ss.getSheetByName('Part Cost Calculator');
// get the named ranges
var namedRanges = calcSheet.getNamedRanges();
// loop through the list of named ranges and delete them
for (var i = 0; i < namedRanges.length; i++) {
namedRanges[i].remove();
}
}
ADDENDUM: - Copy based on Named Ranges
The original so_5466573501 assumes that the parts are in a simple 2 column-list; in which case, Named Ranges are irrelevant.
The following code assumes that the parts are not in a list but scattered, in no particular order, throughout the sheet "Part Cost Calculator". This code is based on obtaining the NamedRanges, identifying the respective Named Range row and column, correlating said row and column to the ENTIRE data range, and then copying the results to the "Saved Parts" sheet. No Named Ranges are created by default on the "Saved Parts" sheet but this can be easily done by using the createnamedranges function (appropriately edited for the correct sheet name).
function so_5466573502() {
//set master spreadhseet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//create variables for calc and save sheets
var calcSheet = ss.getSheetByName('Part Cost Calculator')
var saveSheet = ss.getSheetByName('Saved Parts');
//get the Parts Parameters from Part Cost Calculator
var namedRanges = calcSheet.getNamedRanges();
var numNR = namedRanges.length
//Logger.log("DEBUG: Number of named ranges on Parts Cost Calculator = "+numNR);
// get all the data
var dataRangeValues = calcSheet.getDataRange().getValues();
// create an array to temporarily store results
var resultsarray = [];
// Loop through the array of Named Ranges
for (var x = 0; x < numNR; x++) {
var nrName = namedRanges[x].getName();
var nrRange = namedRanges[x].getRange();
var nrRangerow = nrRange.getRow();
var nrRangecol = nrRange.getColumn();
var nrRangeValue = dataRangeValues[nrRangerow - 1][nrRangecol - 1];
//Logger.log("DEBUG: Named Range-Name: "+nrName+", Range: "+nrRange.getA1Notation()+", Row: "+nrRangerow+", Column: "+nrRangecol+", Value-"+nrRangeValue);//DEBUG
// populate the array with the part name and the part value
resultsarray.push([nrName, nrRangeValue]);
}
// identify the range on the Saved Parts sheet to copy the parts list array.
var saveRange = saveSheet.getRange(1, 1, numNR, 2);
saveRange.setValues(resultsarray);
// sort the results on "Saved Parts"
saveRange.activate().sort({
column: 1,
ascending: true
});
}

Google Apps Script Replace and update cell within a range

I have a Google spreadsheet that I'm trying to remove the word "woo" within a range of cells
So far I've managed to loop through the results and log the results, however I haven't figured how to update that information in the spreadsheet itself.
Any guidance would be welcomed
Thank you
function myFunction () {
var ss = SpreadsheetApp.getActiveSheet().getRange('B:B')
var data = ss.getValues();
for (var i = 0; i < data.length; i++) {
var text = data[i].toString();
var finaltext = text.replace(/woo/g, "");
data[i] = finaltext;
Logger.log(data[i]);
}
}
Use setValues()
Notes:
Usually ss is used as a shorthand for spreadsheet, as it's used on the code for a range it's better to use range as a variable name.
setValues() returns a 2D array, so data[i] returns an array of row values rather than a cell value. To get/set cell values, use data[i][0] notation.
Considering the above replace
var ss = SpreadsheetApp.getActiveSheet().getRange('B:B')
by
var range = SpreadsheetApp.getActiveSheet().getRange('B:B')
then add the following line after the for block.
range.setValues(data);
Regarding text var declaration, replace
var text = data[i].toString();
to
var text = data[i][0].toString();
Using open ended references like B:B could lead to problems. To avoid them be sure to keep the sheet rows at minimum or better instead of using an open ended reference use something like B1:B10.

Resources