Dropdown List deduction - google-sheets

I have a list of 100 employees and 50 dropdowns. I want to select some of the employees in the dropdowns but I want to prevent the user from choosing the same employee more than once.
I want to deduct the chosen employees from the possible dropdown answers. How can I manage to do so?
I tried to filter out the selected employees but it shows an ugly warning sign for those who were selected
you can view my spreadsheet here:
https://docs.google.com/spreadsheets/d/1bzMPC3-SDOjsgZVXHQgmfBnkiTEsa1Pei7p_DybIebY/edit?usp=sharing

You can use the Simple Trigger onEdit(e) to automatically do the job:
The onEdit(e) trigger runs automatically when a user changes the value
of any cell in a spreadsheet [...]
It's not exactly the same as you had before, because the selected values will still be displayed on the list. They just will be removed if they are repeated.
The only change you should do is to remove the current Data Validation from Column D and set a new one with values from Column A.
function onEdit(event){
if (event.range.getColumn() == 4){ //Run only if the edited cell is from column D
var sheet = SpreadsheetApp.getActiveSheet();
var selection = sheet.getRange("D2:D22").getValues();
var editedRow = event.range.getRow(); //Gets the edited row
for (var i = 0; i < selection.length; i++){
//If some value from D is equal to the edited value but in a different Row (so it ignores the inputted value)
if ((i + 2) != editedRow && selection[i][0] == event.value){
sheet.getRange(event.range.getA1Notation()).setValue(""); //Change the new value to empty
}
}
}
}
The function will run every time you select an item in the column D.
Result:
References:
Range
Sheet
setValue

Related

google sheet add button to insert new row that has formula

This is the simplified version of my data. I want to place a button at the bottom of the grey area, so that upon clicking, a new row is inserted above the bottom. the new row must have the formula as the rows before it.
my real formulas are very complicated so I cant use arrayFormula to fulfill the data in new rows.
this a link to my spreadsheet.
You can refer to this sample code that uses a custom menu to insert new row with formula based on the previous row.
Code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Custom Menu')
.addItem('Insert New Row', 'insertRow')
.addToUi();
}
function insertRow() {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
//Exit function if current active sheet is not Sheet1
if(sheet.getName() != "Sheet1"){
return;
}
//insert new row
sheet.insertRowAfter(lastRow);
sheet.getRange(lastRow,2,1,3).copyTo(sheet.getRange(lastRow+1,2));
}
What it does?
Get the last row and the last column that has content in the active sheet using getLastRow() and getLastColumn()
Insert a new row after the last row that has content using insertRowAfter(afterPosition)
Get the range of the last row that has content using getRange(row, column, numRows, numColumns)
Where:
row = your last row that has content
column = column index where you want to start (in the sample sheet it is in column B/ index 2)
numRows = should be 1 (we only want to copy the current last row that has content)
numCols = how many columns to select. In the sample sheet there are 3 columns (column B-D)
Use copyTo(destination) to copy both values and formatting of the range selected in step 3 and paste it in the newly added row. Destination range should be the top-left cell. Since we want to copy it to the new row.I used getRange(last row +1, 2)
Output:
Note:
If you want to use button placed below the grey row, just use insertRow when you assign a script in your button
Please make sure that the last row with content is the row that has formula.
If you want to use the function on a specified list of sheets, you can add this in the sample code. This will exit the function if the current active sheet name is not included in the valid sheets listed
var validSheets = ["Sheet1", "Sheet2"];
if(!validSheets.includes(sheet.getName())){
return;
}
Remove the last comment ... then click on the new menu : this script will add a new line in the active sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('>> Action <<')
.addItem('Copy last row (formulas only)', 'copyLastRow')
.addToUi();
}
function copyLastRow() {
var sh=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var rng=sh.getRange(sh.getLastRow(),1,1,sh.getLastColumn())
rng.copyTo(sh.getRange(sh.getLastRow()+1,1,1,sh.getLastColumn()), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false)
}

How can I make a Google Sheets macro to search all rows for a particular fill color, copy the rows and paste them at the bottom of the sheet?

The rows in my sheet have a fill color in column A of that particular row. I want to be able to use a macro or maybe for loop to search for these rows with the color identifier, copy and paste them below, return to the row where I was and continue the search until the I've hit the bottom of the original list.
Update -
Basically I want to start with a sheet like this.
Google Sheet before macro
and have the end result look like this
Google sheet post macro
If I understand you correctly, you want to loop through each row in your sheet and copy/paste the ones which have a certain background color in column A after the last row. If that's the case, then you could use something along the following lines using Google Apps Script (you would have to create a script bound to your spreadsheet):
function appendRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var color = "#582323"; // Please change accordingly
var firstRow = 1;
var numRows = sheet.getLastRow() - firstRow + 1;
var column = 1;
var numCols = sheet.getLastColumn() - column + 1;
var range = sheet.getRange(firstRow, column, numRows); // Get column A
var backgrounds = range.getBackgrounds(); // Get backgrounds of each cell in column A
for (var i = 0; i < backgrounds.length; i++) { // Iterate through each cell in column A
if (backgrounds[i][0] == color) { // Check background color
var rowToCopy = sheet.getRange(i + 1, column, 1, numCols); // Row to be copied
var lastRow = sheet.getLastRow(); // Row index to copy to
rowToCopy.copyTo(sheet.getRange(lastRow + 1, column, 1, numCols)); // Copy row to the bottom
}
}
}
Notes:
Please change the background color you want to look for.
Check inline comments for more information on what the script is doing, line by line.
Reference:
getBackgrounds
getRange
copyTo
I hope this is of any help.

Need help adapting script to multiple days of the week

I found this code in another post. For Google Sheets, basically it copies the color formatting in the "Status" tab and colors in the matching cells in "Monday".
function colorCodeRevised() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var lr=ss.getSheetByName("Monday").getLastRow() // get last row of sheet1
var lc=ss.getSheetByName("Monday").getLastColumn() //get last column of sheet1
var lr1=ss.getSheetByName("Status").getLastRow() // get last row of sheet2
var lc1=ss.getSheetByName("Status").getLastColumn() ////get last column of sheet2
var sv=ss.getSheetByName("Monday").getRange(5,2,1,lc-15).getValues() // get vehicles. startrow,startcolumn,numrows to return,numcolumns to return
var sn=ss.getSheetByName("Monday").getRange(6,1,lr-5,1).getValues() // get names
var s1=ss.getSheetByName("Status").getRange(2,1,lr1-2,lc1)//exclude legend. squarebackets is sheet numbermm 0=1, 1=2
var rng1=s1.getValues() // get sheet2 data
var rng2=s1.getBackgrounds() // get background colors of dheet2 data
var test= sn.length
var test1= sv.length
var test2=rng1[0].length
var col=1 //column for vehicles on sheet1
for(var m=0;m<sv[0].length;m++){ //for each vehicle
col=col+1 //add one to vehicle column
for(var n=0;n<sn.length;n++){ //for each name
for(var i=0;i<rng1.length;i++){ //loop sheet2 data
for(var j=0;j<rng1[0].length;j++){
if(rng1[i][j].indexOf(sv[0][m])>-1 && rng1[i][j].indexOf(sn[n][0])>-1){ //if sheet2 data cell contains vehicle and name
var c=ss.getSheetByName("Monday").getRange(n+6, col).setBackground(rng2[i][j]) //set color of vehicle and name on sheet1
}}}}}
}
I have a very similar spreadsheet to this but I am struggling to make it run not only for Monday but for all the days of the week. I could make 6 identical scripts but I feel like it would be too taxing having the sheet run 7 scripts every time a change needs to be made. The cells that I want to be colored are in the exact same pattern/order as Monday. For example if C6 on Monday is red, C6 on Tuesday should also be red. Can anyone help me make this script color the same cells from Tuesday-Sunday as it does Monday, without it taking 7 times as long to run?
To your specific question; I think all you really need to do is add a loop with a list of the sheets you want to modify. From there, you can just make everything a variable. That solution is shown last.
Before I just let you off with that though, I'd like to suggest a few changes ^_^
Getting that code-sample and making it work for your sheet was great! I liked the concept and I get where you are with organizing all of that data. I made some changes that (I think) might help you out.
Most of these changes were made with the intention of bringing the logic out of the script and into the sheet. The phenomenal thing about using the formulas in the sheets is that they are optimized by Google very well. If you could break down what you're looking to do into code-snippets that Google has implemented, things get much faster.
Suggested changes:
Status page
Changed to matrix of users and roles. Each role that someone plays has an x in it. In the future, you can populate this matrix based on a form input if that's what you're going for.
Set A1 to contain all of the conditional formatting needed to properly color the table on the day pages.
Manually colored the role headers since I didn't want to re-do all the conditional formatting in A1 and hierarchical conditional formatting isn't a thing.
Day pages
Each cell in the color table now has a formula in it that will set the value to the role based on whether the user in that row has an x in that role on the status page.
Based on the text in those cells, they are colored to have the class' selected color for the text and background.
The script
Can be configured at the top with a list of pages to change and the location of the cell with the formatting.
I wish I could have created the formatting rules in the script, but that functionality isn't available yet. Hopefully it will be implemented when Google gets to this issue
Grabs the cell with the formatting
Loops through each page
Gets the color table
Copies the formula (in the script) and the formatting to the table
Finally, it adds a custom menu at the top that can be used to call the function named "Script tools".
Advantages
You only need to copy the formulas and formatting to each sheet once
When changes are made in status, they are immediately reflected on the proper page
Alternate solution
link to my sheet
link to make an editable copy in your drive
/* Loops through all whitelisted sheets and applies a pre-defined format to the table on each.
*
* Michael Kenworthy 12/21/16
*/
//Set-up variables
var whitelist = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
var colorKeySheet = "Status"
var colorKeyFormatCell = "A1"
var colorTableRange = "B6:M"
var doc = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
function formatting() {
statusSheet = doc.getSheetByName(colorKeySheet);
formatCell = statusSheet.getRange(colorKeyFormatCell);
for(var i=0; i<whitelist.length; i++){
sheet = doc.getSheetByName(whitelist[i])
colorTable = sheet.getRange(colorTableRange);
cell = colorTable.getCell(1, 1)
cell.setFormula('if(not(isblank(INDIRECT("Status!R"&MATCH($A6,Status!$A:$A,0)&"C"&MATCH(B$5,Status!$1:$1,0),false))),B$5,)')
formatCell.copyTo(cell, {formatOnly: true});
cell.copyTo(colorTable)
}
}
function onLoad(){
// Or DocumentApp or FormApp.
ui.createMenu('Sheet tools')
.addItem('Apply formatting to day sheets', 'formatting')
.addToUi();
}
Solution to original question
var whitelist = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
function colorCodeRevised() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var lr1=ss.getSheetByName("Status").getLastRow() // get last row of sheet2
var lc1=ss.getSheetByName("Status").getLastColumn() ////get last column of sheet2
var s1=ss.getSheetByName("Status").getRange(2,1,lr1-2,lc1)//exclude legend. squarebackets is sheet numbermm 0=1, 1=2
var rng1=s1.getValues() // get sheet2 data
var rng2=s1.getBackgrounds() // get background colors of dheet2 data
for(var sheetNum=0;sheetNum<whitelist.length;sheetNum++){
var lr=ss.getSheetByName(whiltelist[sheetNum]).getLastRow() // get last row of sheet1
var lc=ss.getSheetByName(whiltelist[sheetNum]).getLastColumn() //get last column of sheet1
var sv=ss.getSheetByName(whiltelist[sheetNum]).getRange(5,2,1,lc-15).getValues() // get vehicles. startrow,startcolumn,numrows to return,numcolumns to return
var sn=ss.getSheetByName(whiltelist[sheetNum]).getRange(6,1,lr-5,1).getValues() // get names
var col=1 //column for vehicles on sheet1
for(var m=0;m<sv[0].length;m++){ //for each vehicle
col=col+1 //add one to vehicle column
for(var n=0;n<sn.length;n++){ //for each name
for(var i=0;i<rng1.length;i++){ //loop sheet2 data
for(var j=0;j<rng1[0].length;j++){
if(rng1[i][j].indexOf(sv[0][m])>-1 && rng1[i][j].indexOf(sn[n][0])>-1){ //if sheet2 data cell contains vehicle and name
var c=ss.getSheetByName(whiltelist[sheetNum]).getRange(n+6, col).setBackground(rng2[i][j]) //set color of vehicle and name on sheet1
}
}
}
}
}
}
}

How to remove conditional formatting in sheets using script

I'm currently using a modified script that allows me to copy an entire line from sheet#1, create a new line at the top of sheet #2, paste the copied line to that sheet, and delete the old line from sheet#1.
This is done often throughout the day by many users. The function is onEdit.
This is the script :
function onEdit(e) {
var ss = e.source;
var activatedSheetName = ss.getActiveSheet().getName();
var activatedCell = ss.getActiveSelection();
var activatedCellRow = activatedCell.getRow();
var activatedCellColumn = activatedCell.getColumn();
var activatedCellValue = activatedCell.getValue();
var URGENCE = ss.getSheetByName("List"); // source sheet
var COMPLET = ss.getSheetByName("Comp"); // target sheet
// if the value in column K is "x", move the row to target sheet
if (activatedSheetName == URGENCE.getName() && activatedCellColumn == 11 && activatedCellValue == "x")
{
COMPLET.insertRows(2,1);// insert a new row at the second row of the target sheet
var rangeToMove = URGENCE.getRange(/*startRow*/ activatedCellRow, /*startColumn*/ 1, /*numRows*/ 1, /*numColumns*/ URGENCE.getMaxColumns());
rangeToMove.moveTo(COMPLET.getRange("A2"));
URGENCE.deleteRows(activatedCellRow,1); // delete row from source sheet
}
}
Recently this has been crashing my sheet. Everytime someone puts an "x" in Column K, the sheet will stall and most of the time, it will crash and chrome will kill the page.
I could be wrong, but the problem I'm guessing is that most of the rows in sheet#1 have conditional formatting. When the line is copied, it also copies the conditional formatting. This results in my sheet#2 having hundreds of repeating conditional formatting: this sheet is VERY slow to open. IT could also be because this document is shared with about 30 people who view it and edit it very often: perhaps onEdit isn't the right function here?
Is there a simple script I could add to my function which would strip the conditional formatting on the pasted line? I don't need the conditional formatting in my sheet#2 and for some odd reason I can't find an answer to this anywhere.
Found this function from here.
clearFormats()
Clears the sheet of formatting, while preserving contents. Formatting
refers to how data is formatted as allowed by choices under the
"Format" menu (ex: bold, italics, conditional formatting) and not
width or height of cells.
Sample code:
function testKillFormatting (nameOfSheet) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(nameOfSheet);
sheet.clearFormats();
}

Can you count links within a range?

I have many Google sheets that require manually hyperlinking (to specific unique documents) after other users have inserted values, but it is time-consuming to search through many sheets for cells yet to be linked. A basic solution would be to use COUNTA to get the number of cells within a range containing text, and a second function to count the number of links, showing the difference. I've tried many permutations of COUNTA and COUNTIF using wildcards but nothing seems to be able to recognise formulas. Is there a function within Google Sheets of getting the number of hyperlinked cells within a range?
If you are referring to urls in cells (like: www.google.com), you can try:
=SUM(ArrayFormula(N(ISURL(A3:A))))
Change range to suit.
This will not work if you are using =HYPERLINK() function.
EDIT: If you want to count the cells with text, but exclude the =Hyperlink() formulas (AND empty cells) you can try this custom function:
function countF(range) {
var r = SpreadsheetApp.getActive().getRange(range),
formulas = r.getFormulas(),
count = 0;
r.getValues()
.forEach(function (r, i) {
r.forEach(function (c, j) {
if (c && formulas[i][j].substring(1, 10) !== "HYPERLINK") count += 1;
})
})
return count;
}
This custom function can be used in your spreadsheet by entering
=COUNTCELLS("Sheet1!A1:A2")
If you want to exclude all formulas from your count, change the if-statement to:
if (c && !formulas[i][j]) count +=1
Make sure you always mention the sheet name.
EDIT2: to count the number of formulas, you can try something like this:
function countFormulas(range) {
var count = 0;
SpreadsheetApp.getActive()
.getRange(range).getFormulas()
.forEach(function(r) {
r.forEach(function(c) {
if (c.charAt(0) == '=') count += 1;
})
})
return count;
}
I suggest the following. The formula assumes the cells to check for Hyperlinks are in column A with header (adjust formula to your need). Select A2. Right click and select Conditional Formatting. Enter the following:
Apply to range
A2:A
Format cells if
Choose 'Custom formula is' from dropdown list and enter:
=AND(NOT(ISFORMULA(A2)),NOT(ISBLANK(A2)))
Choose the formatting style you want.
This will format and non blank cell not containing a formula. (No Hyperlink)
Two other options to get just a count:
In a column, lets say B enter the following formula(Note that ISFORMULA does not work in array formulas like ISBLANK does.) Copy the formula down. It will return FALSE if there is a Hyperlink and TRUE if there is not.
=NOT(ISFORMULA(A2))
Then to count use:
=countifs(B2:B,"TRUE",B2:B,"<>''")
The other option is script:
function noFormula() {
var ss=SpreadsheetApp.getActiveSpreadsheet()
var s = ss.getSheets()[0];// [0] is Sheet1
var lr=s.getLastRow()
var rng =s.getRange(2, 1, lr-1, 1) //get column A data. Assumes header row.
var data=rng.getFormulas()
count=0
for(i=0;i<data.length;i++){
var hasFormula=data[i][0]
var eqSign=hasFormula.substring(0,1) //looks for first character "=". If there are formulas other than Hyperlinks change to substring(0,2) to look for "=H".
if(eqSign !="="){ //Not equal to"="
count = count+1
}}
var c=s.getRange(1,2).setValue(count)//Sheet1 B1
}

Resources