Simple relative cell referencing in google code - cell

I have made this virtual inventory with buttons that copy and paste values to various sheets for different types of reports. The code might not be optimal I am not much of a programmer but I'm trying my best. now I have the same button in multiple places and I want it to copy values in cells relative to the position of the button itself but I am not sure how to reference a cell in a relative manner in the getRange fucntion.
here is the code:
function Go() {
var ss = SpreadsheetApp.getActiveSpreadsheet ();
var sheet = SpreadsheetApp.getActiveSheet();
var destSheet = ss.getSheetByName("Fiche");
var lastRow = destSheet.getLastRow();
var source = ss.getRange ('(rowid-3)(colid)');
var checkbox = sheet.getRange (3,3);
var destColumn = ss.getRange ('B10').getValues ();
source.copyTo(destSheet.getRange(lastRow + 1,1), {contentsOnly: true});
if (checkbox.getValue() == 'vrai' ) {
var source = ss.getRange ('B9');
source.copyTo(destSheet.getRange(lastRow + 1, destColumn), {contentsOnly: true});
source.copyTo(destSheet.getRange(lastRow + 1, 2), {contentsOnly: true});
}
else {
var nombre = ss.getRange ('D5').getValues() ;
destSheet.getRange(lastRow + 1, destColumn).setValue(nombre);
destSheet.getRange(lastRow + 1, 2).setValue(nombre)
}
I want all (B10),(B9), etc. format cells to be replaced with relative cell positons. I have tried with (colID)(rowID) but it doesn't seem to work

I believe your goal as follows.
You want to retrieve the cell coordinate when a button on Spreadsheet is clicked.
Modification points:
Unfortunately, in the current stage, when a button on Spreadsheet is clicked, there are no methods for directly retrieving the information where button is clicked.
So when you want to use the button on Spreadsheet, if you want to retrieve the information, it is required to prepare each script for each button. But I thought that this might be different from the direction you expect.
In this answer, in order to retrieve the information where the button is clicked, I would like to propose the following 2 patterns as the workarounds. In these patterns, the event object is used. By this, the information of the button can be retrieved. This is used.
Pattern 1:
In this pattern, a cell is used as the button using the simple trigger of OnSelectionChange. When the cell "B3" is used as the button like above image, the script is as follows.
Sample script:
In this script, for example, when you want to use the cell "B3" of "Sheet1" as the button, please set "B3" to buttonRanges. And, set sheet.getSheetName() != "Sheet1". When when you want to use the cell "B3" and "B4" as the button, please set "B3" and "B4" to buttonRanges.
function onSelectionChange(e) {
const range = e.range;
const sheet = range.getSheet();
const buttonRanges = ["B3"];
if (sheet.getSheetName() != "Sheet1" || !buttonRanges.includes(range.getA1Notation())) return;
const row = range.getRow(); // This is the row number.
const column = range.getColumn(); // This is the column number.
}
In this case, when the cell "B3" is clicked, this script is run. And row and column are the row and column number of the cell.
Because the cell is used as the button, you can put the value to the cell.
Pattern 2:
In this pattern, a checkbox is used as the button using the OnEdit trigger. When the cell "B3" is used as the button like above image, the script is as follows.
Sample script:
In this script, for example, when you want to use the cell "B3" of "Sheet1" as the button, please set "B3" to buttonRanges. And, set sheet.getSheetName() != "Sheet1". When when you want to use the cell "B3" and "B4" as the button, please set "B3" and "B4" to buttonRanges.
function onEdit(e) {
const range = e.range;
const sheet = range.getSheet();
const buttonRanges = ["B3"];
if (sheet.getSheetName() != "Sheet1" || !buttonRanges.includes(range.getA1Notation()) || !range.isChecked()) return;
const row = range.getRow(); // This is the row number.
const column = range.getColumn(); // This is the column number.
}
In this case, when the checkbox is checked, the script is run. When the checkbox is unchecked, the script is not run.
Because the checkbox is used as the button, you cannot see the text in the cell.
References:
Simple Triggers
Event Objects
Related question
Button change text display every after click
This question is for achieving the switching button.

Related

Transactions in Google Sheet - Move value from, to

I'm trying to make a document to manage my finances on google sheet, actually, I would like to be able to track the transactions I make between my accounts.
I made this sheet to be able to sum things up.
Actually, I would be able to tell the document i'm making a transaction from - to (in that case, from content 1 to content 3) and to add a new value.
I don't know how to tell google sheet to "move" 25 from content 1 to content 3 or any other content.
Thanks for the precious help.
You can use an Apps Script onEdit trigger so fire the transactions, and use checkboxes to track which transaction should be fired, so that the transaction takes place whenever the corresponding checkbox is checked.
First, add the checkboxes to the transaction rows by selecting the appropriate cells and click Insert > Checkbox.
Then, open the script bound to your spreadsheet by selecting Tools > Script editor, copy the following function, and save the project. Now every time a checkbox is checked, the corresponding transaction takes place in B2:E3, and when it is unchecked the transaction gets undone (the from and the to exchange places, and the money goes the other way):
function onEdit(e) {
var range = e.range;
var col = range.getColumn();
var row = range.getRow();
var checkbox = e.value;
var sheet = range.getSheet();
if (col === 6 && row > 8) {
var from = sheet.getRange(row, 3).getValue();
var to = sheet.getRange(row, 4).getValue();
var value = sheet.getRange(row, 5). getValue();
var valuesToUpdate = sheet.getRange("B2:E2").getValues();
var fromIndex = valuesToUpdate[0].findIndex(contents => contents === from);
var toIndex = valuesToUpdate[0].findIndex(contents => contents === to);
var fromRange = sheet.getRange(3, fromIndex + 2);
var toRange = sheet.getRange(3, toIndex + 2);
if (checkbox === "TRUE") { // MAKE TRANSACTION
fromRange.setValue(fromRange.getValue() - value);
toRange.setValue(toRange.getValue() + value);
} else if (checkbox === "FALSE") { // UNDO TRANSACTION
fromRange.setValue(fromRange.getValue() + value);
toRange.setValue(toRange.getValue() - value);
}
}
}
This function will fire every time the spreadsheet is edited, but you only want to update the transaction summary whenever the edited cell is a checkbox and this checkbox is checked. The function is checking for that, using the information passed to the onEdit function through the event object (e), which contains information on the edited cell (its value, its range, etc.):
Reference:
onEdit(e)
Event Objects: Edit

Is there any way to add a template doc at top of an another google document using google scripting?

I am trying to add a template doc into an existing google doc.The template is being added, but next time when i am trying to add the template again the template is appending at the bottom of the existing google doc but i want to insert the template at the top.
You can do this by getting the Body of one document and appending its child Elements to the current document.
function addtemplate() {
var thisDoc = DocumentApp.getActiveDocument();
var thisBody = thisDoc.getBody();
var templateDoc = DocumentApp.openById(''); //Pass in id of doc to be used as a template.
var templateBody = templateDoc.getBody();
for(var i=0; i<templateBody.getNumChildren();i++){ //run through the elements of the template doc's Body.
switch (templateBody.getChild(i).getType()) { //Deal with the various types of Elements we will encounter and append.
case DocumentApp.ElementType.PARAGRAPH:
thisBody.appendParagraph(templateBody.getChild(i).copy());
break;
case DocumentApp.ElementType.LIST_ITEM:
thisBody.appendListItem(templateBody.getChild(i).copy());
break;
case DocumentApp.ElementType.TABLE:
thisBody.appendTable(templateBody.getChild(i).copy());
break;
}
}
return thisDoc;
}
It sounds like your goal is to choose the position of the document where the content is added?
One option is to add the template at your current cursor location.
In the example below I have two functions. The first function creates a menu in Google Docs when I open the document (usually a few seconds delay).
The second function attempts to identify the position of my cursor. If it's successful it will insert the date at my cursor position.
Since I've created a menu item I don't have to go to the script editor to trigger this function.
function onOpen() {
// Add a menu item in Google Docs.
DocumentApp.getUi().createMenu('Insert Menu')
.addItem('Insert Current Date', 'insertCurrentDate')
.addToUi();
}
function insertCurrentDate() {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
// Attempt to insert text at the cursor position. If insertion returns null,
// then the cursor's containing element doesn't allow text insertions.
var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
var element = cursor.insertText(date);
if (element) {
element.setBold(true);
} else {
DocumentApp.getUi().alert('Document does not allow inserted text at this location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
It's also possible that you want to clear the previous template before pasting the new one in? You can do that with the clear() function and then run the rest of your code.
body.clear()

Change Text on Status Strip Label inside a click event on Table Layout Panel moves Form to Selected Control

I have a very weird issue which I cannot manage to fix.
The Problem
Inside a Windows Form I have a StatusStrip and a tableLayoutPanel. That StatusStrip contains one label which will change its text depending on the row clicked. The tableLayoutPanel is set to autoScroll since the content is bigger than the size of my form.
Each row will have different controls. You can find buttons, labels, text boxes or checkboxes.
I'm able to select the row and change the text according to the selected row. The problem comes when I have scrolled down and then click on the table. For some reason, the Form will move to the last selected Control within the table.
For instance, If I have clicked inside a textbox, and I scroll down, where I cannot see the textbox, when I click on a table row. The form will automatically move to show the textbox.
It seems to me that for some reason, when I change the text it must repaint the whole table and then it moves to the last selected control.
What Have I tried
Move the table inside a panel.
Move the panel to another panel.
As for now, the panel is removed, doesn't seem to be necessary.
Originally I had 6 labels, removed them all to ensure it happens with just one.
If I don't change the text, but for instance, shows a message inside the Debug then the problem disappears, which for me it indicates that the problem resides inside the "change text" event.
** EDITED **: If I change a label inside the table, the problem is gone. So it seems to be a combination with the table + the status label.
** EDITED **: If I move the auto scroll to the form instead of the table. Then the problem is gone. But this is not what I want because then, my status bar won't be visible since it will be on the button and I need it to keep visible.
** EDITED **: If I use a menu strip the problem is still there. If I move the status Stript. The problem is still there.
** EDITED **: If I remove the panels and use a label inside the form. The problem persist.
The Code
I will keep code to a minimum and will add more if it is necessary.
This is where I update the toolStriptStatusLabel:
System::Void updateSelectedRow(int row) {
if (row == selectedRow)
return;
selectedRow = row;
Command ^cmd = commandsList[row];
commandToolStripStatusLabel->Text = cmd->name;
}
This is my click event:
System::Void tableLayoutPanel1_Click(System::Object^ sender, System::EventArgs^ e) {
System::Drawing::Point ^point = GetRowColIndex(
tableLayoutPanel1,
tableLayoutPanel1->PointToClient(Cursor->Position
));
updateSelectedRow(point->Y);
}
This is where I find the Row I clicked:
System::Drawing::Point ^GetRowColIndex(TableLayoutPanel ^tlp, Point point) {
if (point.X > tlp->Width || point.Y > tlp->Height)
return nullptr;
int w = tlp->Width;
int h = tlp->Height;
array<int> ^widths = tlp->GetColumnWidths();
int i;
for (i = widths->Length - 1; i >= 0 && point.X < w; i--)
w -= widths[i];
int col = i + 1;
array<int> ^heights = tlp->GetRowHeights();
for (i = heights->Length - 1; i >= 0 && point.Y < h; i--)
h -= heights[i];
int row = i + 1;
return gcnew Point(col, row);
}

Ember context passed to a view

I'm trying to figure out what's wrong about sending action from parentView to one of its children view:
I've made a PhotoUploadView used to resize and then upload images; it adds canvas drawing the resized image in a div inside its template:
<div class="img-list">
//here the canvas will be added
</div>
The action "saveImages" in this view, acts like this:
var list = this.$('.img-list');
$.each(list.children(), function(index, value) {
//here the code to save
}
But this action is not called directly; because I need to save not only the images but also some records (an offer record and many products records, children of the offer; the images are associated to the product record);
So I have the action "save" on the parentView that is like this:
//save records
offer.save().then(function(savedOffer) {
newProducts.forEach(function(product, indexP) {
product.set('offer', savedOffer);
product.save().then(function(savedProduct) {
}
}
}
//save photos by cycling the PhotoUploadViews that are inside ProductViews that are inside the mainView
this.get('childViews').forEach(function(view, index) {
if (index >= 4) { //the childView from the 4th are the ProductViews
var productId = view.get('product').get('id');
var folder = 'offer-' + controller.get('model').get('id') + '/product-' + productId + '/';
view.get('childViews')[0].send('saveImages', folder, productId); //the first childView of a ProductView is the UploadView
}
});
Well, this works and save the images correctly when you add images to an existing offer with existing product; but when you are creating a new offer, it fails since the folder will becone "offer-undefined/product-undefined" because of course you must wait the records to be saved in order to get their ID;
So I'm trying now to move the send action into the .then callback of product save:
var childViews = this.get('childViews'); //the childView starting from the 4th are the productsViews
offer.save().then(function(savedOffer) {
newProducts.forEach(function(product, indexP) {
product.set('offer', savedOffer);
product.save().then(function(savedProduct) {
var currentPview = (childViews[4 + indexP]); //get the productView associated with the current product
var productId = savedProduct.get('id');
var folder = 'offer-' + savedOffer.get('id') + '/product-' + productId + '/';
currentPview.get('_childViews')[2].send('saveImages', folder, productId); //the object at index 2 of _childViews array is the photoUploadView
Here, the folder is built correctly but after sending action, the saveImages action crashes saying that list is undefined; trying to log the value of "this" inside "saveImages" I can see that also its value is undefined; Someone can please explain why calling the action from one point, it works, and calling it inside the .then callback of product save it doesn't?
I also would like to understand why in the first case I can do
.get('childViews')[0]
to get the PhotoUploadView, but in the second I must do
.get('_childViews')[2]
since using get('childViews) it doesn't work anymore; What is the difference between childViews and _childViews? And why _childViews has more elements than childView?

How do I add a ComboBox to a TreeView column?

In Gtkmm, I want to have a Gtk TreeView with a ListStore, and have one of the columns in the list be a ComboBoxText. But I can't seem to figure out how to do it.
What I currently have looks like:
class PlayerListColumns : public Gtk::TreeModelColumnRecord
{
public:
PlayerListColumns()
{ add(name); add(team);}
TreeModelColumn<string> name;
TreeModelColumn<ComboBoxText*> team;
}
Then when setting the TreeView (the player_list_view object)
PlayerListColumns *columns = new PlayerListColumns();
Glib::RefPtr<ListStore> refListStore = ListStore::create(*columns);
player_list_view->set_model(refListStore);
ComboBoxText *box = manage(new ComboBoxText());
box->append("Blah");
box->append("Blah");
box->append("Blah");
TreeModel::Row row = *(refListStore->append());
row[columns->name] = "My Name";
row[columns->team] = box;
The column "name" shows up just fine, but no ComboBox. I'm almost positive that simply having a pointer to a combo box as the column type is wrong, but i don't know how it's supposed to go. I do get GTK warning:
GLib-GObject-WARNING **: unable to set property text' of typegchararray' from value of type `GtkComboBoxText'
Which seems to indicate (from a small bit of Googling) that there isn't a default renderer for non-basic types. But I haven't been able to find any examples of how to set one up, if that were the problem. All the tutorials only show TreeViews with primitive data types.
Anyone know how to put a ComboBox into a TreeView?
Okay, I haven't gotten it working 100%, but this example class should get you on the right track:
http://svn.gnome.org/svn/gtkmm-documentation/trunk/examples/book/treeview/combo_renderer/
Basically you need to add a Gtk::TreeModelColumn<Glib::RefPtr<Gtk::ListStore> > to your columns class and a Gtk::TreeModelColumn<string> to hold the selected data.
Then, to make a column a combobox, you have to add:
//manually created column for the tree view
Gtk::TreeViewColumn* pCol = Gtk::manage(new Gtk::TreeViewColumn("Choose"));
//the combobox cell renderer
Gtk::CellRendererCombo* comboCell = Gtk::manage(new Gtk::CellRendererCombo);
//pack the cell renderer into the column
pCol->pack_start(*comboCell);
//append the column to the tree view
treeView->append_column(*pCol);
//this sets the properties of the combobox and cell
//my gtkmm seems to be set for Glibmm properties
#ifdef GLIBMM_PROPERTIES_ENABLED
pCol->add_attribute(comboCell->property_text(), columns->team);
//this is needed because you can't use the ComboBoxText shortcut
// you have to create a liststore and fill it with your strings separately
// from your main model
pCol->add_attribute(comboCell->property_model(), columns->teams);
comboCell->property_text_column() = 0;
comboCell->property_editable() = true;
#else
pCol->add_attribute(*comboCell, "text", columns->team);
pCol->add_attribute(*comboCell, "model", columns->teams);
comboCell->set_property(text_column:, 0);
comboCell->set_property("editable", true);
#endif
//connect a signal so you can set the selected option back into the model
//you can just have a column that is not added to the view if you want
comboCell->signal_edited()
.connect(sigc::mem_fun(*this,&ComboWindow::on_combo_choice_changed));
EDIT ABOVE
I think something along the lines of using a Gtk::CellRendererCombo* is the way to go in your PlayerListColumns
http://developer.gnome.org/gtkmm/stable/classGtk_1_1CellRendererCombo.html
(I haven't made a working test yet, but I got the idea from:
http://developer.gnome.org/gtkmm-tutorial/unstable/sec-treeview.html.en#treeview-cellrenderer-details)