Appending dynamic values to cell in google sheets - google-sheets

I have a cell (G7) that is dynamically linked to a website with importHTML, and it has number that is updated periodically. Is there a way to store the current value of that dynamic cell and add it to another cell, and the keep doing that every time it changes?
Cell G7 is my dynamic number and Cell E2 where I want to keep appending changes to G7. So if right now G7 is $16.28, I want to store that in E2, and then let’s say a few months from now G7 updates to $14.5, then I want it to add $14.5 to the $16.28 in cell E2 rather than replace it. So the new number upon updating G7 should be $30.78. Would I have to make another tab and store each iteration of G7 into a list and add them together with SUM in E2? How can I store the number in G7 when certain conditions are met use dates from cells C7, H7, and I7 automatically?
An example of a date condition being if C7<= H7, and I7 is equal to Today's date then append this number from G7 to E7.
Is there another way of doing this without making a history list in another sheet? In a scripting language I think this would be written as E2+=G7. While G7 is constantly changing it is being appended to E2.
Here is a Demo I made of the sheet im working on.
https://docs.google.com/spreadsheets/d/1Wk1kMGeZuVEcSdsnXnGIzdwPHLqYKoyqlD1yYcGXxXs/edit?usp=sharing

Simple Trigger onEdit(e) runs when a user changes a value in a spreadsheet
The onEdit event trigger has an object passed by parameter that you can use depending on the Google Product used, for instance, Spreadsheet events, where the e.source object represents the Google Sheets file to which the script is bound.
For example:
function onEdit(e){
// Set a comment on the edited cell to indicate when it was changed.
var range = e.range;
range.setNote('Last modified: ' + new Date());
}
By having the code above, when a change is made to a single cell, this code runs and sets a note every time the cell is changed/saved.

Related

Dynamically referencing different sheets by changing sheet range argument depending on another cell's value

[Goal]
I want to be able to have a cells with formulas (such as COUNTIFS) that can change the referencing sheet range depending on the value in another cell.
[Example sheet]
To demonstrate, I've created the below example simple Spreadsheet where it has 3 different sheets. 2 with raw data (2022 Data, 2023 Data) and another with a table that will use the both sheets' raw data.
https://docs.google.com/spreadsheets/d/1Viz3SUibpaIRu77SLwLxjfcd0ZOVmHPQpu8jTdCL92I/edit?usp=sharing
Cell A2 is for selecting the date (formatted to only show the month) and cell E4 is referencing A2 to get the date/month that was selected. D4 and all month cells adjacent to each references each other to get the incremental months.
Cell range B5:E7 is using the COUNTIFS formula to count how many emails or chats were there for that month. You'll notice that the range argument is referencing as: '2022 Data'!.
What I want to do here is to create a COUNTIFS formula with a range argument that can refer to the corresponding sheet depending on the year of that column. For example for cell B5, the month is Jan 2023, I want it to refer to the 2023 Data sheet instead of 2022 Data sheet in a dynamic way.
Obviously, I could add another COUNTIFS so that it can take 2023 Data sheet's data into consideration, however, I'd have to change the formula every time it's a new year.
Using the QUERY function as an example, I know that you can refer to a cell within the string argument if you use the double quotation and the ampersand symbol (example: "&H1&") to get out of the string. I tried doing something similar (example: '"&B4&" Data'!) but nothing worked.
[Question]
Is there somehow where I could potentially change the cell referring range dynamically depending on the value of another cell?
you can use INDIRECT:
=COUNTIFS(INDIRECT("202"&RIGHT(B4, 1)&" Data!A:A"),B4)

Use Arrayformula to auto-populate column in Google Sheets based on condition

I'll do my best to explain this. So, I want to use Arrayformula to autofill column based on a condition.
=IFERROR(QUERY(ARRAYFORMULA(IF((Research!$B$1:$B$100)="Yes",REGEXEXTRACT(Research!$A$1:$A$100,".*"),)),"WHERE Col1 is not null")).
It does what it's supposed to, but the problem comes if that condition changes at any point (so it's not true anymore) the value in the cell filled with the array will get deleted but will also offset all the other rows after it (same happens if I insert new row with 'Yes' value in between other rows, in my Research sheet from where I extract my data from).
Is there any way if I need to make changes to the condition in the sheet from where I extract data > and not offset everything else in the sheet where I use the array formula? (either delete the entire row if the value doesn't meet the condition anymore, or insert new row if it meets the condition (not just replace the value in previous cell in its spot, cuz then all the other fields are mismatched). I'm a beginner with excel, I hope that makes sense. Sheet ex
Condition in Main Sheet > Result in Array sheet
(these are the ok examples)
Changed value to yes for Agency 3 > Inserted in Agency's 5 place > and offsets everything after it
Please refer to the spreadsheet for my examples.
Method A: Separate the sheets of input and output
Method B: Input on Research and output on Initiative
Method C: Use Google Apps Script to 'avoid' offset upon change of Take? value. (example is not provided)

How To Transfer A Value From One Cell To Another In Google Sheets

I have an interesting situation where every second column in my Google Sheet represents the amount of items at various stations. What I'm trying to accomplish is to automatically adjust the amounts of these values when a transfer value is entered into a cell between these columns.
For example, here are the first few cells on the sheet:
Cell B5: Data entered here should be added to the value in C5, then clear
Cell C5: Displays AMOUNT C
Cell D5: Data entered here should be subtracted from value in C5, added to the value in E5, then clear
Cell E5: Displays AMOUNT E
See this attached example. Values are added to the yellow cells, and what they need to be doing to their adjacent cells is described above each one.
Some examples:
Adding the number 5 to Cell B5 needs to change the value of C5 from 72 to 77, and then B5 needs to clear.
Adding the number 12 to J6 needs to change the value of I6 from 36 to 24, the value of K6 from nothing to 12, and then J8 needs to clear.
Adding the number 32 to R5 needs to change the value of Q5 from 41 to 9, the value of S5 from 1 to 3, and then R5 needs to clear.
Adding the number 5 to Cell V6 needs to change the value of U6 from 5 to nothing, and then V6 needs to clear.
I would prefer using formulas, and since I can avoid circular reference errors by going to File/Spreadsheet Settings/Calculation and changing the Max number of iterations to 1 (Threshold at 0.05), I can use a formula like =C5+B5 in Cell C5. Is there a way to add to this formula so that B5 is cleared after its value is added to C5? And how would I then add the functionality of subtracting a value entered in D5 from C5, and then clear D5 as well?
Does anyone have any ideas? It would be much appreciated!
I think this onEdit() trigger is what you need. Also see the documentations on Apps Script and Spreadsheet App.
For example, in your sheet, an implementation for requirement 1 can be as follows.
function onEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var tab = sheet.getSheetByName('Item Transferring');
sheet.setActiveSheet(tab); \\<---
var cell = e.range;
user_input = cell.getValue();
if (cell.getRow() == 5 && cell.getColumn() == 2){ \\ it's probably best that you read the row and column indices of B5 and C5 from a helper tab/sheet in case you decide to move B5 and C5 later.
var cell2 = tab.getRange(5,3);
cell2.setValue(cell2.getValue()+user_input);
cell.clear({contentsOnly: true});
SpreadsheetApp.setActiveRange(cell); \\<--- use this in conjunction with setActiveSheet. Either use both or use neither.
}
}
Set up an onEdit trigger for the function onEdit, and the desire effect will occur.
Note that in your scenarios, the edits are always on single cells. Sometimes, edits can occur to multiple cells simultaneously. Make sure there is no ambiguity in your interface. Also the protect function of Google Sheet may come in handy.
Comment:
Do try to create a different interface where you are not as reliant on change per edit. You can easily run into problems with synchronization. A final sheet that does not take a lot of inputs frequently may be fine. It nevertheless slows down your regular activities.
As well, you should probably have a cell that displays the most recent edit.
EDIT: regarding generalizing the code and applying the above example, you can do something like this:
function process_input(row_input,col_input,input,output,func){
// row_input and col_input are the cell indices you are watching
// input is the range object that the edit trigger passes in
// output is the range object that contains the cell you want your edit to happen to
// func contains the formula you want in the output cell
if (input.getRow()==row_input,input.getColumn()==col_input){
output.setValue(func(input,output));
input.clear({contentsOnly: true});
}
}
As an example that can apply to the rest of your problems, your scenario 1 from earlier would require a function as below. Be careful that a user input can be accidentally non-numeric.
function update_add(input,output){
if (!isNaN(input.getValue()) && isFinite(input.getValue()){
return input.getValue()+output.getValue()
}else{
return output.getValue()
}
}
You would write a simple function like the above for every kind of update you want to have. To put it all together, using your scenario 1 as an example, which is to monitor B5 and update B6 using add recipe, you would do
function onEdit(e){
...
output = tab.getRange(5,3);
process_input(5,2,e.range,output,update_add)
}
As mentioned earlier, it's better for you to pull the indices of the cells you are watching from a separate sheet -- as oppose to hardcoding the numbers 5, 3, 2. To implement a full solution for all of your scenarios, you can simply loop through all the cells you need to watch by update method and then loop through all possible update methods.
You do need to implement the exact code yourself. On Stackoverflow, we only discuss methods and how they work. We discuss using minimally self-contained examples. We can't hand codes to complete people's projects. That won't be a sustainable kind of interaction.
The intended take-away for you from this answer are the various Apps Script utilities linked and described with sample codes and the advices on generalization. That's it. If there are questions about a utility, please read the linked documents; and if you still have questions after, open another post with a specific focus.

Is there a Google Sheets formula to put the name of the sheet into a cell?

The following illustration should help:
Here is what I found for Google Sheets:
To get the current sheet name in Google sheets, the following simple script can help you without entering the name manually, please do as this:
Click Tools > Script editor
In the opened project window, copy and paste the below script code into the blank Code window, see screenshot:
......................
function sheetName() {
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}
Then save the code window, and go back to the sheet that you want to get its name, then enter this formula: =sheetName() in a cell, and press Enter key, the sheet name will be displayed at once.
See this link with added screenshots: https://www.extendoffice.com/documents/excel/5222-google-sheets-get-list-of-sheets.html
You have 2 options, and I am not sure if I am a fan of either of them, but that is my opinion. You may feel differently:
Option 1: Force the function to run.
A function in a cell does not run unless it references a cell that has changed. Changing a sheet name does not trigger any functions in the spreadsheet. But we can force the function to run by passing a range to it and whenever an item in that range changes, the function will trigger.
You can use the below script to create a custom function which will retrieve the name:
function mySheetName() {
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
return key;
}
and in the cell place the following:
=mySheetName(A1:Z)
Now if any value in a cell in that passed range changes the script will run. This takes a second to run the script and sets a message in the cell each time any value is changed so this could become annoying very quickly. As already mentioned, it also requires a change in the range to cause it to trigger, so not really helpful on a fairly static file.
Option 2: Use the OnChange Event
While the run time feels better than the above option, and this does not depend on a value changing in the spreadsheet's cells, I do not like this because it forces where the name goes. You could use a Utilities sheet to define this location in various sheets if you wish. Below is the basic idea and may get you started if you like this option.
The OnChange event is triggered when the sheet name is changed. You can make the code below more sophisticated to check for errors, check the sheet ID to only work on a given sheet, etc. The basic code, however, is:
function setSheetName(e) {
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('K1').setValue(key);
}
Once you have saved the code, in the script editor set the Current Project's On Change Trigger to this function. It will write the sheet name to cell K1 on any change event. To set the trigger, select Current project's triggers under the Edit menu.
If you reference the sheet from another sheet, you can get the sheet name using the CELL function. You can then use regex to extract out the sheet name.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
update:
The formula will automatically update 'SHEET NAME' with future changes, but you will need to reference a cell (such as A1) on that sheet when the formula is originally entered.
Not using script:
I think I've found a stupid workaround using =cell() and a helper sheet. Thus avoiding custom functions and apps script.
=cell("address",[reference]) will provide you with a string reference (i.e. "$A$1") to the address of the cell referred to. Problem is it will not provide the sheet reference unless the cell is in a different sheet!
So:
where
This also works for named sheets. Then by all means adjust to work for your use case.
Source: https://docs.google.com/spreadsheets/d/1_iTD6if3Br6nV5Bn5vd0E0xRCKcXhJLZOQqkuSWvDtE/edit#gid=1898848593
EDIT:
I've added another workaround in the document that makes use of =formulatext() and some traditional text functions. By referencing to a cell in the current sheet using it's full address, i.e. Sheet1A1 you are able to use formulatext() to extract only the sheet name.
Here is my proposal for a script which returns the name of the sheet from its position in the sheet list in parameter. If no parameter is provided, the current sheet name is returned.
function sheetName(idx) {
if (!idx)
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
else {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var idx = parseInt(idx);
if (isNaN(idx) || idx < 1 || sheets.length < idx)
throw "Invalid parameter (it should be a number from 0 to "+sheets.length+")";
return sheets[idx-1].getName();
}
}
You can then use it in a cell like any function
=sheetName() // display current sheet name
=sheetName(1) // display first sheet name
=sheetName(5) // display 5th sheet name
As described by other answers, you need to add this code in a script with :
Tools > Script editor
An old thread, but a useful one... so here's some additional code.
First, in response to Craig's point about the regex being overly greedy and failing for sheet names containing a single quote, this should do the trick (replace 'SHEETNAME'!A1 with your own sheet & cell reference):
=IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), "")
It uses a lazy match (the ".+?") to find a character string (squotes included) that may or may not be enclosed by squotes but is definitely terminated by bang dollar ("!$") followed by any number of characters. Google Sheets actually protects squotes within a sheet name by appending another squote (as in ''), so the SUBSTITUTE is needed to reduce these back to single squotes.
The formula also allows for sheet names that contain bangs ("!"), but will fail for names using bang dollars ("!$") - if you really need to make your sheet names to look like full absolute cell references then put a separating character between the bang and the dollar (such as a space).
Note that it will only work correctly when pointed at a different sheet from the one that the formula resides! This is because CELL("address" returns just the cell reference (not the sheet name) when used on the same sheet. If you need a sheet to show its own name then put the formula in a cell on another sheet, point it at your target sheet, and then reference the formula cell from the target sheet. I often have a "Meta" sheet in my workbooks to hold settings, common values, database matching criteria, etc so that's also where I put this formula.
As others have said many times above, Google Sheets will only notice changes to the sheet name if you set the workbook's recalculation to "On change and every minute" which you can find on the File|Settings|Calculation menu. It can take up to a whole minute for the change to be picked up.
Secondly, if like me you happen to need an inter-operable formula that works on both Google Sheets and Excel (which for older versions at least doesn't have the REGEXREPLACE function), try:
=IF(IFERROR(INFO("release"), 0)=0, IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), ""), MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255))
This uses INFO("release") to determine which platform we are on... Excel returns a number >0 whereas Google Sheets does not implement the INFO function and generates an error which the formula traps into a 0 and uses for numerical comparison. The Google code branch is as above.
For clarity and completeness, this is the Excel-only version (which does correctly return the name of the sheet it resides on):
=MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255)
It looks for the "]" filename terminator in the output of CELL("filename" and extracts the sheet name from the remaining part of the string using the MID function. Excel doesn't allow sheet names to contain "]" so this works for all possible sheet names. In the inter-operable version, Excel is happy to be fed a call to the non-existent REGEXREPLACE function because it never gets to execute the Google code branch.
I have a sheet that is made to used by others and I have quite a few indirect() references around, so I need to formulaically handle a changed sheet tab name.
I used the formula from JohnP2 (below) but was having trouble because it didn't update automatically when a sheet name was changed. You need to go to the actual formula, make an arbitrary change and refresh to run it again.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
I solved this by using info found in this solution on how to force a function to refresh. It may not be the most elegant solution, but it forced Sheets to pay attention to this cell and update it regularly, so that it catches an updated sheet title.
=IF(TODAY()=TODAY(), REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1"), "")
Using this, Sheets know to refresh this cell every time you make a change, which results in the address being updated whenever it gets renamed by a user.
I got this to finally work in a semi-automatic fashion without the use of scripts... but it does take up 3 cells to pull it off. Borrowing from a bit from previous answers, I start with a cell that has nothing more than =NOW() it in to show the time. For example, we'll put this into cell A1...
=NOW()
This function updates automatically every minute. In the next cell, put a pointer formula using the sheets own name to point to the previous cell. For example, we'll put this in A2...
='Sheet Name'!A1
Cell formatting aside, cell A1 and A2 should at this point display the same content... namely the current time.
And, the last cell is the part I'm borrowing from previous solutions using a regex expression to pull the fomula from the second cell and then strip out the name of the sheet from said formula. For example, we'll put this into cell A3...
=REGEXREPLACE(FORMULATEXT(A2),"='?([^']+)'?!.*","$1")
At this point, the resultant value displayed in A3 should be the name of the sheet.
From my experience, as soon as the name of the sheet is changed, the formula in A2 is immediately updated. However that's not enough to trigger A3 to update. But, every minute when cell A1 recalculates the time, the result of the formula in cell A2 is subsequently updated and then that in turn triggers A3 to update with the new sheet name. It's not a compact solution... but it does seem to work.
To match rare sheets names like:
Wow!
Oh'Really!
''!
use the formula:
=SUBSTITUTE(REGEXEXTRACT(CELL("address";Sheet500!A1);"'?((?U).*)'?!\$[A-Za-z]+\$\d+$");"''";"'")
or
=IF(NOW();SUBSTITUTE(REGEXEXTRACT(FORMULATEXT(A1);"='?((?U).*)'?![A-Za-z]+\d+$");"''";"'")) if A1 is formula reference to your sheet.
if you want to use build-in functions:
=REGEXEXTRACT(cell("address";'Sheet1'!A1);"^'(.*)'!\$A\$1$")
Explanation:
cell("address";'Sheet1'!A1) gives you the address of the sheet, output is 'Sheet1'!$A$1. Now we need to extract the actual sheet name from this output. I'm using REGEXEXTRACT to match it by regex ^'(.*)'!\$A\$1$, but you can either use more/less specific regex or use functions like SUBSTITUTE or REPLACE

Obtain the value of function now() in Google spredsheet

In Google script sheet, in cell A1 I input the function now() and returns current time (e.g. 13:00). I want to fix the value. But if I make any change in the cell, the value will be changed. What I can do is to copy cell A1 and selective paste value in cell B1 and then change the format of B1 as time. Is there any function that can obtain the value in A1 and fix it in another cell?
Many thanks!
Another question I don't understand but perhaps:
select the another cell
key Ctrl+Shift+Enter.
If I have misunderstood, perhaps Google Docs time stamp? from Web Apps may be hepful.

Resources