Hiding Columns based on a Cell Values - google-apps-script

I am trying to hide columns based on the selection in A2.
Here is the code I am working with and I am hard stuck.
function onEdit(e) {
var myRange = SpreadsheetApp.getActiveSheet().getRange("A:J");
//Let's get the row & column indexes of the active cell
var row = e.range.getRow(1);
var col = e.range.getColumn(0);
//Check that your active cell is within your named range
if (col >= myRange.getColumn() && col <= myRange.getLastColumn() && row >= myRange.getRow() && row <= myRange.getLastRow()) {
if e.myRange === "Renewal" ? myRange.hideColumns(5)
}
}
If anyone could point me in the right direction it would be greatly appreciated.

Based on your code, I assume you want to hide column 5 (E) if dropdown in A2 is "Renewal". If that's what you want, then you got many issues in your script.
Code:
function onEdit(e) {
// get current sheet
var sheet = e.source.getActiveSheet();
// get row and column of edited cell
var row = e.range.getRow();
var col = e.range.getColumn();
// make sure to only hide/show column if edited cell is A2 in 'Sheet1'
if (col == 1 && row == 2 && sheet.getSheetName() == 'Sheet1') {
// if value of A2 in Sheet1 is Renewal, hide columns, if not Renewal, then show the same columns back
if (e.value === "Renewal") {
sheet.hideColumns(5, 2); // hide column 5-6 (E-F)
sheet.hideColumns(8, 1); // hide column 8 (H)
}
else {
sheet.showColumns(5, 2); // show column 5-6 (E-F)
sheet.showColumns(8, 1); // show column 8 (H)
}
}
}
Mistakes:
getRow() and getColumn() gets the current row and column of the range respectively. You don't pass a parameter here
You do not need to identify if your edited cell is within the range A:J, you only need to specify that row and column should be pointing to A2 (and a specific sheet if needed be which is considered in )
Ternary operators do not need if statement before it and it always need the else part. Thus I added showColumns to show the hidden column if A2 is not Renewal.
hideColumns() is a sheet method, not range, thus you need to get the sheet you currently edit. Additionally, it accepts 2 parameters, the index where it starts hiding a column and how many columns you need hidden.
Output:
Resources:
getRow/getColumn
hideColumns/showColumns
Ternary operators

Related

How to show specific columns based on cell value in google sheets

I'm trying to write script that will achieve the following logic:
If cell J1 has a value of 1, show columns 1-10. If cell J1 has a value of 2, show columns 1-18. If cell J1 has a value of 3, show columns 1-26. If cell J1 has a value of 4, show columns 1-36.
Here' what I have so far:
function onOpen(e) {
hideVersions_(e);
}
function hideVersions_() {
// get current sheet
var sheet = e.source.getActiveSheet();
// get row and column of edited cell
var row = e.range.getRow();
var col = e.range.getColumn();
if (col == 10 && row == 1 && sheet.getSheetName() == 'Design') {
if (e.value === "2") {
sheet.hideColumns(19, 17); // hide column 19-36 (S-AJ)
sheet.showColumns(1,17); // show column 1-18 (A-R)
}
if (e.value === "3") {
sheet.hideColumns(27, 9); // hide column 27-36 (AB-AJ)
sheet.showColumns(1,25); // show column 1-26 (A-AA)
}
if (e.value === "4")
sheet.showColumns(1,35); // show column 1-36 (A-AJ)
}
else {
sheet.hideColumns(11, 25); // hide column 11-36 (K-AJ)
sheet.showColumns(1,9); // show column 1-10 (A-J)
}
}
As I tried to get this to work I noticed you had an Underscore on your Function Name
function hideVersions_() {
That kept me from running and testing that Function.
You also Passed e from the onOpen Event into the hideVersion Function, but did not declare e as a parameter.
Instead of the onOpen Event do you want to use the onChange Event? Even though you might be making other changes we can modify the script to only look at cell J1 on a specific sheet. You'll notice in the code below I added an if statement to check if e is Null, this allowed me to test the file in the editor with out the triggering event.
I think your logic in your if statement can be simplified, not sure why you are checking if the sheet is a certain sheet of the spreadsheet. I also tend to grab the Value I want instead of letting the e event be the most recently edited cell. This is why I removed the row and col check from your first if statement.
In your if statements you "stringed" your values, but I am assuming you are putting numbers into the cell, and therefore your === is expecting numbers on both sides. Removing the quotes fixed that issue.
In your if statements you hide the new cells and then show cells, I think this can be simplified by Showing all cells and then hiding the new cells.
Below is the code that I got to work that completes what you asked for:
function onOpen(e)
{
hideVersions(e);
}
function hideVersions(e)
{
// get current sheet
if ( e == null) // When you run this Function in Editor
{
var sheet = SpreadsheetApp.getActiveSheet();
}
else
{
var sheet = e.source.getActiveSheet();
}
// get Control Cell J1
var controlValue = sheet.getRange(1,10).getValue(); // J1 is Row 1 Col 10
Logger.log(controlValue);
var lastColumn = sheet.getLastColumn();
if (sheet.getSheetName() == 'Design')
{ //since we grabed the cell explicitly, only Need to check SheetName
if (controlValue === 2)
{
Logger.log("Hiding s-AJ");
sheet.showColumns(1, lastColumn); // show All
sheet.hideColumns(19, 17); // hide column 19-36 (S-AJ)
}
if (controlValue === 3)
{
Logger.log("Hiding AB-AJ");
sheet.showColumns(1, lastColumn) //Show All
sheet.hideColumns(27, 9); // hide column 27-36 (AB-AJ)
}
if (controlValue === 4)
{
Logger.log("Showing all");
sheet.showColumns(1,lastColumn); // show all
}
else
{
Logger.log("Hiding K-AJ");
sheet.showColumns(1, lastColumn); // Show All
sheet.hideColumns(11, 25); // hide column 11-36 (K-AJ)
}
}
}
This is what the onOpen() event object looks like:
{"authMode":"LIMITED","range":{"columnEnd":1,"columnStart":1,"rowEnd":1,"rowStart":1},"user":{"email":"redacted","nickname":"redacted"},"source":{}}
Please note: no e.value

Adding a row in Google Sheets (Specific conditions)

I am working on a script that I can't get quite right. I need to get a script that will allow me to insert an empty row above the previous top row.
So, row 2 is always the top, but when row 2 is edited, I want it to automatically create another row above it, taking its place as row 2. I was sort of able to achieve this by creating a column I've called "Key" and when I add the text "AUTOADD" to that column it will autoadd a row above. However, I would ideally like to not have to add that text to get it to work.
Here is what I have:
function onEdit(e) {
// get sheet
var sheet = SpreadsheetApp.getActive().getSheetByName("ChatAgenda");
// Get the edited range
var editedRange = e.range;
// check if cell A2 was edited
if (editedRange.getA1Notation() === "A2") {
// check if value is a desired value
if (editedRange.getValue() === "AUTOADD") {
// if yes to both, insert new row
sheet.insertRowBefore(2);
}
}
}
How about inserting a checkbox in A1 of ChatAgenda
Then use this code:
function onEdit(e) {
const sh = e.range.getSheet();
if (e.range.columnStart == 1 && e.range.rowStart == 1 && e.value == "TRUE") {
e.range.setValue("FALSE");//Reset the checkbox
sh.insertRowBefore(2);
}
}
When you check the checkbox it adds and row and resets the checkbox

Google Sheet: Show first data validation value if cell is empty

Good afternoon everyone,
I am looking for a way for my dropdown list to show the first value if the cells A18 and F18 are empty. The data validation range is from cell X18 to AA18 (4 values).
So basically, when I enter the name 'Test', it will fetch the data: "Healer", "Tank", "Paladin" and "Mixed DPS" from another tab and display it in the cells X18 to AA18. Using data validation a dropdown list is being generated with these values. However, as soon as I enter a name, I want the default value of the dropdown list to be the value of X18.
So: if A18 is empty, the value of F18 should be matching X18. (if no name is given, there wont be anything in F18 so it should stay empty)
If I understand correctly just put the formula in Cells F18:F.
=IF($A18<>"",$X18,"")
If column A is not empty then fetch the value in column X, otherwise blank (or select from dropdown). Take a look at the sheet you linked, I have updated it.
Selecting from the dropdown will overwrite the formula, if this is the issue you're referring to your only fix is to create a helper column or utilize scripts.
UPDATE
In order to accomplish this with scripts you can add the following:
function onEdit(e) {
var editRange = { // A18:A250
top : 18,
bottom : 250,
left : 1,
right : 1
};
//Get sheet from which the event occured
var range = e.range
var sheet = range.getSheet();
// Exit if wrong sheet
if (sheet.getSheetName() != "War Board") return;
// Exit if we're out of range
var thisRow = e.range.getRow();
if (thisRow < editRange.top || thisRow > editRange.bottom) return;
var thisCol = e.range.getColumn();
if (thisCol < editRange.left || thisCol > editRange.right) return;
//Set default if value is not blank
if (!range.isBlank()) range.offset(0, 5).setValue(range.offset(0, 23).getValue());
//Set blank if value is blank
if (range.isBlank()) range.offset(0, 5).setValue("");
}
This will set the value of F to the corresponding value in X column if a name is given in column A. If the cell in column A is emptied it empties cell F.

I am trying to set the value of multiple cells when the value of once cell changes in google sheets

I am trying to set the values of several cells in the same row of a cell that I am changing.
IF the value in AJ2 is True then the range AK2:AX2 should also be true.If I change AJ2 to false, then I should be able to uncheck any of the values in the range and they would then be false. I 'sort of' have this logic working. IF I have AJ2 checked and uncheck AK2, when I uncheck AJ2 it rechecks AK2.
I also need this to happen on all rows if I change the value in the column of AJ for their rows. not just row 2. I am fairly new to working with sheets and could use some help.
function onEdit(e) {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange("AJ2");
var range =ss.getRange("AK2:AX2")
var activeCell = ss.getActiveCell();
if(activeCell.getColumn() == 36&&ss.getActiveSheet().getName()=="MasterData") {
if (Cell = "TRUE")
range.setValue("TRUE")}
}
Try this
function onEdit(e) {
const sheet = e.source.getActiveSheet();
const cell = e.range;
// AJ = column 36 (master column)
if(sheet.getName() == "MasterData" && cell.getColumn()==36 && cell.isChecked()){
sheet.getRange(cell.getRow(),37,1,14).setValue('TRUE')
}
// individual columns : 37 (AK) to 50 (AX)
if(sheet.getName() == "MasterData" && cell.getColumn()>=37 && cell.getColumn()<=50 && !cell.isChecked()){
sheet.getRange(cell.getRow(),36,1,1).setValue('FALSE')
}
}
explanation
when a box is checked in column 36 (AJ = 'master column'), all the boxes of the same row between 37 to 50 (AK to AX) will be checked
when an individual box is unchecked between column 37 to 50 (AK to AX) the master box of the same row will be also unchecked
reference
onEdit trigger
The onEdit(e) simple trigger returns an event object.
The event object contains the information about the spreadsheet that was edited, which you use instead of the "SpreadsheetApp.getActiveSpreadsheet()"
To access the information in the event object, you need to use the 'e':
function onEdit(e) {
//the sheet that was edited
var sheet = e.source.getActiveSheet();
//the cell that was edited
var cell = sheet.getActiveCell();
//the row number of the cell that was edited
var row = cell.getRow();
//the column number of the cell that was edited
var column = cell.getColumn();
From there, proceed as you normally would with sheets and ranges.
To update multiple cells at once, you can set the range with getRange(row, column, numRows, numColumns) and then setValues(values). Note that it's setValues(), not setValue().

Script - Add a row beneath, based on conditional criteria

Dear Oracles of the script,
I have been trying to get some script to automatically add a row beneath the one I have inputted on, but only if the Balance is anything BUT zero. If it's zero, I don't want another row adding.
I've tried a few scripts and looked around the site, and tried them with triggers with on edit, but they just seem to add a row, despite me trying to state a condition for them to trigger.
function onEdit(event) {
var eventRange = event.range;
if (eventRange.getColumn() == 12) { // 12 = column of input that triggers it
var columnXRange =
SpreadsheetApp.getActiveSheet().getRange(eventRange.getRow(), 13,
eventRange.getNumRows(), 12); /// column number it affects
var values = columnXRange.getValues();
for (var i = 0; i < values.length; i++) {
if (!values[i][0]) { // If cell isn't empty
values[i][0] = '0';
}
}
columnXRange.setValues(values);
}
}
function Clear(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('AGL');
sheet.getRange('N4:N').clearContent();
}
function AddRow() {
var sheet = SpreadsheetApp.getActiveSheet();
if (sheet.getName() == "AGL") {
var activeCell = sheet.getActiveCell();
if (activeCell.getColumn() == 13) {
var Balance = sheet.getRange('N:N');
if (Balance != '0'); {
sheet.insertRowAfter(activeCell.getRow());
}
}
}
}
In column N, I have an array formula working out the balance of stock in, against stock out.
In column M, I have a script running that will add a 0 when something is put into column L. I also have a script that erases the output of the array formula, so they don't get tangled up with each other.
I would like, when editing a row, when I place a figure in column L or M, and if the balance in Column N is greater than 0, I would like a new row adding underneath. (If you can get it to add the values from A & B, that'd be a bonus, but not fussy.) If the balance is 0, I don't want a row adding.
Currently, I have mixed results with it just adding a row every time I edit column N.
Requirement:
Add a row when columns L or M are edited and the value in column N is greater than 0 (& if possible, add values from columns A & B to the new row).
Solution:
This is pretty much all you need for your script. I've added comments to explain what each part is doing so it should be pretty easy to follow.
function onEdit(e) {
//define edited sheet, row number and column number
var sh = e.source.getActiveSheet();
var row = e.range.getRow();
var col = e.range.getColumn();
//get value of column N for edited row
var val = sh.getRange(row, 14).getValue();
//if columns L or M are edited and column N is greater than 0
if ((col === 12 || col === 13) === true && val > 0) {
//insert row below edited row
sh.insertRowAfter(row);
//get values of columns A and B of edited row
var vals = sh.getRange(row, 1, 1, 2).getValues();
//set values in columns A and B
sh.getRange(row+1, 1, 1, 2).setValues(vals);
}
}
Notes:
I haven't included any of your other functions, only adding a row, you can incorporate these in this function if you desire.
You won't be able to run this script manually at all (it'll fail on the first line), it'll just run automatically when the sheet is edited.
References:
Event Objects
Class Sheet