Carry out equations using Google Sheet Script to update database values - google-apps-script

So I'm trying to create a simple Elo model for our table tennis league at work, I'm using the spreadsheet to generate match ups and then depending upon the winner going in and manually updating the rankings.
I attempted to try and do this (As seen below) but I was blissfully unaware that set.formula was definitely not the correct coding to be using.
Is there a way for me to carry out what I've outlined below, I essentially want to be able to click a button for Player A or Player B and have their Elo rank update on the back end and then generate a new match combination? Also how do I update the record based on a variable? Everyone has a unique player number but is there a function similar to VLOOKUP that will let me find a record and perform a formula?
I've put as many sheet callouts in the code below as I can:
var sheet =SpreadsheetApp.getActive().getSheetByName("Data");
var cell = sheet.getRange("=VLOOKUP("!MatchC18,A:C,3,False")
cell.setFormula ("=SUM(VLOOKUP(!MatchC18,A:C,3,FALSE)+!MatchA6*(1-E$4))");
cell.setFormula ("=SUM(VLOOKUP(!MatchE18,A:C,3,FALSE)+!MatchA7*(0-F$4))");
var sheet =SpreadsheetApp.getActive().getSheetByName('Match');
var cell = sheet.getRange ("C18");
cell.setFormula("=TRUNC(RANDBETWEEN(100,632))");
var sheet =SpreadsheetApp.getActive().getSheetByName('Match');
var cell = sheet.getRange ("E18");
cell.setFormula("=TRUNC(RANDBETWEEN(100,632))");
Any help will be massively appreciated!
Thanks!

As commented, your post is too broad.
Anyhow, to help you in any ways, you may use the following as additional references.
There's already an existing issue 456 in google-apps-script-issues tracker on using bulk methods such as setValues, setFormulas, etc.
and based from the thread, this issue hasn't been totally fixed yet. You may, however, try to use the given work around.
For the usage of VLOOKUP in Google Spreadsheets, more information can be found in Find Data in Google Spreadsheets with VLOOKUP.

Related

Updating Google Sheet with WooCommerce Order

I need to be able to automatically update a google sheet file every time an order is placed through WooCommerce.
I've found the solution below, but using this each individual item ordered is listed as a new row. I'd like the order to be grouped under the order number and the item quantities separated into appropriate columns instead.
https://www.tychesoftwares.com/export-woocommerce-orders-to-google-sheets-in-realtime/
Below is a Google Sheet we are manually updating at present to show you what i mean.
Example
Is there a way to send the WooCommerce orders directly through to Google Sheets in this format?
Thanks so much in advance for any advice!
Yes it looks possible.
I know nothing about WooCommerce, but I believe you can sort out the received data in any way you want.
Look, the last line in their script appends the received data as a new row:
sheet.appendRow([timestamp,order_number,order_created,order_status]);
As far as I can see, the data contains the four elements:
timestamp
order_number
order_created
orders_status
Instead, you can put these elements into any cell on your table. Something like this, for example:
var ss = Spreadsheet.GetActiveSheet();
ss.getRange('A10').setValue(timestamp); // timestamp goes to A10
ss.getRange('B20').setValue(order_number); // order_number goes to B20
ss.getRange('C30').setValue(order_created + order_status); // created + status go to C30
The same way you can add any of these elements to some existing value in some cell, etc. For example:
var old_value = ss.getRange('A2').getValue(); // get value from the cell A2
var new_value = old_value + order_number; // add with order_number
ss.getRange('A2').setValue(new_value); // put the sum back into the cell A2
The main problem is up to you. You have to figure out:
what exactly the elements you're receiving (number, names)
how exactly you want to sort them out (what to add to what... what to put where... etc)
I can't understand it from the example picture.
Here is some reference documentation on Apps Script:
Main Page - Introducing Apps Script.
Sheets Guide - Introduction to Sheets with Apps Script.
Sheets Reference - Where you will find all the details of everything you can do with Sheets in Apps Script.
Remove Duplicate Rows - A good small tutorial that will teach you the basics of Sheets and Ranges and how to manipulate them.
To export all my WooCommerce orders on a scheduled basis, I used a ready-made solution.
I used a WooCommerce API and JSON client. It worked smoothly: I got the WooCommerce API, and the JSON client was implemented in the tool already.
You just need to choose endpoint in the JSON client to get the required data. I exported all orders once a month, so I used the base URL http:// mydomain /wp-json/wc/v3/orders and my endpoint was orders.
You can check this article to understand better how it works for your purpose.
And here is WooCommerce API documentation.
I assume that setting up an export through the Apps Script is more flexible (and based on the answer above, it's working indeed), but I'm not a code guy. So I searched for an easier solution, and the API + JSON client helped.
Hope you'll find it helpful.
I would like to suggest using WooCommerce Google Sheet Plugin

How to create a script to merge several sheets in another one?

Sory for my English, this is not my strength!
I am working for a NGO that charges training sessions.
We have a google sheet that compiles datas about participants at each training days one by one in different spreadsheets.
So my yearly document is composed of something like 30 spreadsheets.
I would like to create one more spreadsheet that would merge all the data from other tabs in order to :
- be able to see quickly who has not payed yet his bill
- calculate the total amount made
I know I can do it by using the Filter function but it is really time-consuming for so many spreadsheets and if I add a training session I would have to change the formula. Moreover, I will be forced to do it each year.
So I would like to create a button to import all the data in a new spreadsheet.
You will find an example of the sheet with only 2 spreadsheets here :
https://docs.google.com/spreadsheets/d/1-RxzUGJFXnU3_mJ3Qj0MCTpwPTlnmgIT439AchyrRrE/edit?usp=sharing
I hope you would be able to help me!!
Thanks and happy new year :D
Merging Sheets in another sheet in same spreadsheet.
You will need the id for spreadsheet named 'CopiDdeFCCE' the other parameter will default to 'CopieDdeFCCE'.
function mergeSpreadsheet(ssid,shname){
var shname=shname || 'CopieDdeFCCE';
var ss=SpreadsheetApp.openById(ssid);//id of spreadsheet named 'CopieDdeFCCE' in your case
var sh=ss.getSheetByName(shname);//sheetname of sheet where other sheets are merged into again in your case its named 'CopieDdeFCCE'
if(!sht){ss.insertSheet(shname);}
var allshts=ss.getSheets();
for(var i=0;i<allshts.length;i++){
if(allshts[i].getName()!=shname){//do this for all sheets except shname
var shi=allshts[i];
var rg=shi.getDataRange();
var vA=rg.getValues();
shi.getRange(sh.getLastRow() + 1, 1,shi.getLastRow(),shi.getLastColumn()).setValues(vA);
}
}
}
Just to be clear.
What Google calls the spreadsheet is the file that contains all of the tabs (i.e. sheets).
In your first comment you said the following: I would like to merge all the 28 sheets of a file called "CopieDdeFCCE" to a new sheet of the same file.
But now in your question you say: I would like to create a button to import all the data in a new spreadsheet.
You stated in your last comment that your command looks like this: mergeSpreadsheet("1KC6kHcgtLZ93S4-r4wOwHFOG6Rq3mesGRKv26Ttnm9E","CopieDdeFFCE")
But clearly that's not the id of the example and the example does not have a sheet with that name.
So my question is: What exactly do you want?
Very sory I did not receive any notification of your reply because it was an edit and when I came to see if you wrote something I looked at the bottom of the site. :/
First of all, happy new year and thank you again for your help!!
Here are the precisions you asked :
1° Indeed, I would like to merge all the 28 sheets of a file called "CopieDdeFCCE" to a new sheet of the same file. To be more accurate, I give you the link of the exact location of the document with some examples of sheets: link.
2° Secondly, I will create a button to update all the data easily. But I think I know how to do that, so forget that question for now ;)
3° In the document I put enclosed, do we agree that the "id" is : 1KC6kHcgtLZ93S4-r4wOwHFOG6Rq3mesGRKv26Ttnm9E ??
Thanks again for all your time!

How to write an onOpen triggered script without using Activate() methods

Good morning,
I am having an issue with a piece of script which will open the spreadsheet at the first available row after a data table. I am fairly new to this, but as I understand it from research, the onOpen trigger will not work for scripts featuring Activate() methods (which I assume are things like getActiveRange() and setActiveRange() etc.).
I'd really like for this to work, but I can only do it currently by placing a button at the top of the sheet which the user has to click to run the script. I'm at a loss as to how to write in a different way, and have spent ages googling but only get things which don't help me much at all. My code is as below, any help you can give in writing it without using Activate() methods would be very much appreciated. Thanks, MB
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange("A2");
var rowCount = range.getValue() + 3;
var newRange = ss.getRange("A" + rowCount);
SpreadsheetApp.setActiveRange(newRange); };
The value on line 4 refers to a value in a cell which is counting the number of rows in the dataset (I had issues trying to count this using script because there are other columns in the dataset which throw functions like getLastRow()).
As mentioned in issue 3928 there is no way (as of now, september 2014) to set a selection on a cell/range/sheet from a triggered function.
This issue was closed as "wont fix" but recently reopened - probably because a lot of people were very disappointed (to use a polite word) - so I suggest you star this issue to increase its visibility and its priority.
In the mean time I'm afraid there is not much we can do except continue to use old version spreadsheet in which this works without problem.
About what you said about counting the last row in a single column, this has been the subject of one of the most popular thread on this forum, look at the suggested solutions there (and also in other similar threads).

Workaround for not losing cell's reference because of user doing sorting, while script checks cells value

I have been struggling with the following situation for almost the whole last week and it would be awesome if someone could give me some hint.
The situation:
1. Script finds a particular value in, lets say, 'Sheet1', and gets the row number of the cell containing this value.
2. Since script has found this value, it executes a bunch of actions like creating new spreadsheet and copying numerous 'Sheet1' from dozen other spreadsheets to this newly created spreadsheet, and comparing/ analyzing data.
The problem.
- While script is doing a bunch of other actions, user is able to rearrange cells by, for example, sorting A to Z, which changes the address of previously found cell.
Here is the code that I used in order to verify this:
function WhatHappensIfUserSorts () {
var ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rng = sh.getRange("B17"); //Lets say that script finds this cell according to some rules
Utilities.sleep(10000);
rng.setValue("Test Value");
}
Question:
Might there be any workaround for this?
My current ideas.
1. I was thinking about hiding the filter row in the beginning of the script, but this doesn't help a lot, because users can insert new row in the which will change the addresses of the rows below.
The background.
I am trying to create two way synchronization, meaning, each project member has his/ her own spreadsheet with 'Project X', 'Project Y' etc. sheets and no matter who updates their project sheets, all other users that work on the same project get these updates in their project sheets. These updates that have to be tracked are not just the cell values, these are cell notes as well. And this is the reason why script has to do the bunch of other actions, since CopyTo method does not work between spreadsheets.
During my research I found sheetSpider project, but it seems somewhat different and too complicated from what I need.
A simple suggestion would be to give each row a unique identifier so that you could use it to evaluate the target range again before you write back to the sheet.
get target row's unique ID --> do work --> locate target rows ID and use to determine write range --> write back to sheet.
Alternatively, during the operation you could delete the target row and then use appendRow() to drop the updated version back in.
A third and final suggestion might be to temporarily suspend the permissions for the sheet. See: https://developers.google.com/apps-script/reference/spreadsheet/page-protection#setProtected

Questions about data formatting using UiApp and google spreadsheet

Thank you in advance for any help you can provide. As background, I built a simple UiApp using GAS that I use to populate a google spreadsheet and a calendar with entries about events including time, date, location, etc. I've had it working for awhile but I want to keep improving it and I have a few questions about format and functionality.
1.) I now want the script to copy the information to a second spreadsheet, I've established how to do this, but the second spreadsheet already has some columns in use that I don't want to override and I don't want to just place the info from this Ui into the first 'X' number of columns, is there any easy way to essentially "copy these 5 columns to the first then skip and column and bring in the rest". Here is the code I have for the copy action right now:
var ss = SpreadsheetApp.openById(ssID);
var sheet = ss.getSheets()[0];
sheet.getRange(sheet.getLastRow()+1, 1, 1, 20).setValues([[new Date(), eventTitle, eventDateFrom, eventStartTimeb, eventEndTimeb, eventLocationName, eventLocationCity,eventActivity, eventLeadContact, eventNSLContact, eventContactAttending, eventDepartment, eventStaff, eventMaterials, eventCost, eventIncentive, eventMSTarget, eventSolar, eventNotes,eventRegion]]);
Also, in the same vein as this question, I've been wondering if it is possible to write something that will choose when an entry is copied to the second spreadsheet based on the value of one of the elements. For example, if eventStaff=0 or is blank, the script will copy the designated information to first spreadsheet but not the second.
2.) Date format: I added two listboxes for to capture event time start and event time end and I would like them to show up in the spreadsheet formatted as 00:00 AM/PM, but have only accomplished to get 00:00:00 or whole number so far.
3.) Using multiple elements to fill the location and events portion of calendar entries. This script works to create a basic event with start/end time and a title, but I'd like to use some of the information to fill in the location and description of an event. Is there a way for me to do this or do I need to concatenate those fields into one in able to enter them in the event creation. Current event creation code:
cal.createEvent(eventTitle,eventDateFrom,eventDateTo);
Sorry for the wall of text, if any clarification/additional code sample is needed just ask. Thank you in advance for any help/insight you might be able to provide.
Please don't be offended but I'm afraid your questions are more general programming question than GAS question, by formulating the question you almost answer it by yourself (question 1).
As for question 2, have a look to Utilities.formatDate and you'll get what you want, see also this.
Question 3: see CalendarApp documentation, createEvent, there is a set of optional arguments that suits your needs. - best regards,