Override Conditional Formatting with Worksheet_SelectionChange - excel

I have some code in a worksheet to highlight the row of a selected cell. However, this sheet has conditional formatting which colours some of the rows. The highlighting macro does not work on the rows where the formatting condition is being met (in the sense that the colour of the highlight is not overriding the colour of the conditional formatting).
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Cells.Interior.ColorIndex = xlColorIndexNone
ActiveCell.EntireRow.Interior.ColorIndex = 19 'Highlight row
End Sub
Does anyone know a way around this without removing the conditional formatting?
Eg. can I temporarily disable it for a selected row and re-enable it when the row is unselected?
The formatting is one rule applied to all cells. I figure in theory I could create an independent rule for every row (~500 of them) and then turn that off completely and later reapply it but that seems a little overboard.

There is no need to use ActiveCell in your Worksheet_SelectionChange event macro. That is what Target is/does.
Modify your Worksheet_SelectionChange to be closer to the following.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Target.Name = "mySelection"
Cells.Interior.Pattern = xlNone
Target.EntireRow.Interior.ColorIndex = 19
End Sub
Now you will be constantly redefining a named range for each new selection of cells.
You didn't disclose what the CF rule actually was so I'm going to assume that is highlights cell that are not blank. Modify the existing CF rule to be of the Use a formula to determine which cells to format variety and adjust the following to suit your own CF rule then put it in the Format values where this formula is true: text box.
=AND(A1<>"", ROW(A1)<>ROW(mySelection))
By adding a boolean criteria within an AND function and constantly redefining the mySelection range to the current selection you can override the CF rule's formatting.
        

Related

How to hide columns if a specific row does not match dropdown menu item?

I have a dropdown menu with entries connected to conditional formatting to change the color. This color coding is used in a specific row of each column in the range. When I change the dropdown selection, the cell changes color. I want to be able to make a new selection from the dropdown and have the columns where that specific row does not match the dropdown color be hidden.
Sub EffectFilter(ByVal Effects As Range)
' Dimensionalization
Dim KeyCells As Range
' Initialization
'Setting the range of the CEM Effects
Set KeyCells = Range("Q31:BS31")
'Body
' Detect Background Color of "Filter Effects" cell, Compare to Effects cells Background colors
If Not KeyCells.Interior.ColorIndex = Range("G1:H1").Interior.ColorIndex Then
KeyCells.EntireColumn.Hidden = True
End If
End Sub
This is my code currently. When I pull up the macros tab, it is not present, so I assume it will execute automatically when the color of Range("G1:H1") changes. Cells G1 and H1 have been merged and centered, but nothing currently happens to the columns when I change the dropdown menu selection. Each of the columns in the Range("Q31:BS31") can be or is a different color, but the colors do repeat. I made sure the colors for the dropdown are the exact same as those present in the columns. What I am hoping to do is to select something from the dropdown and the color of that cell will change (This part works already) and the Columns in which Row 31 is not that color will be hidden. I do plenty of things with VBA where you press a button to run a macro, but this is my first time trying to do something automatically like this, so I may be a bit slow to understand at first, but any help is greatly appreciated.
Use the Worksheet_Change event handler (and ensure the code is in the sheet code module, not a regular module).
Use a loop over the columns to be hidden.
You can think of the value of the dropdown (merged cell) as being stored in the top left corner. So use Range("G1"), not Range("G1:H1").
Color or ColorIndex applied by conditional formatting is accessed using .DisplayFormat.Interior.
Private Sub Worksheet_Change(ByVal Target As Range)
' Only proceed if the dropdown changed
If Intersect(Target, Me.Range("G1")) Is Nothing Then Exit Sub
Dim KeyCells As Range, cell As Range
Set KeyCells = Me.Range("Q31:BS31")
' Unhide all columns by default
KeyCells.EntireColumn.Hidden = False
For Each cell in KeyCells
If cell.DisplayFormat.Interior.ColorIndex <> Me.Range("G1").DisplayFormat.Interior.ColorIndex Then
cell.EntireColumn.Hidden = True
End If
Next
End Sub

Highlighting Rows and Columns for both single and multiple selected Cells using Conditional Formatting in Excel

I'm trying to highlight the rows and columns for selected cells in Excel
It's ok when I'm using conditional formatting to highlight only the row and column of single selected cell
But when I try for selecting multiple cells using mouse or keyboard arrow key only the row and column of first selected cell gets highlighted.
Problem is to highlight rows and columns for both single selected cell and multiple selected cell.
though I had to use VBA to Recalculate the formula.
The scenery is this.
the Code is
=OR(CELL("col")=COLUMN(),CELL("row")=ROW())
But the want is to highlight the rows and columns of the cells if I Select multiple cells
So, all the Rows of C8 to C13 need to get highlighted.
I tried but couldn't do it.
I even tried VBA for highlighting rows and columns with the code
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Cells.Interior.ColorIndex = xlColorIndexNone
Target.EntireColumn.Interior.ColorIndex = 6
Target.EntireRow.Interior.ColorIndex = 6
End Sub
The result is this.
but in VBA the highlighting changes the color of a cell and there is also a problem of copy and paste
if this VBA is used then I can't use copy paste a cell
Please if anyone can help?
In your conditional formatting rule add this and apply to the range you want:
=isCellInSelectionRowOrColumn(A1)
In a module add this:
Function isCellInSelectionRowOrColumn(cell As Range)
If Not Intersect(Columns(cell.Column), Selection) Is Nothing _
Or Not Intersect(rows(cell.row), Selection) Is Nothing Then
isCellInSelectionRowOrColumn = True
End If
End Function
And in Worksheet code add:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.Calculate
End Sub
Result is all rows and columns as expansion of your selection get formatted inside the range you apply the rule to:

Excel - Force recalculation when different cell is selected

A bit of context:
I recently discovered that the following formula returns the address of the cell that is currently selected (or if a range is selected, returns the address of the upper-left most cell in the range):
= CELL("address")
At first, I thought this formula would be useful for conditional formatting, since it could be used as part of a condition to only format the cell that is selected (e.g. the conditional formatting rule could be something like = CELL("address")=ADDRESS(ROW(),COLUMN())), but I am facing an obstacle.
The formula is volatile, but volatile functions only update either when:
A cell in the worksheet is changed
F9 is pressed on the keyboard
All that said, my question is: Is there a way to have a cell automatically recalculate whenever a different cell is selected with a mouse click? Even volatile cells won't update from this condition, because selecting a different cell, in itself, won't cause any data in the cells to change.
Of course, it could be updated manually by pressing F9 after selecting a different cell, but I am wondering if there is a way to automate this.
You can use the Worksheet_SelectionChange() event in VBA.
Open your VBE (Alt+F11), find your workbook in the VBAProject pane (upper left) and double click your worksheet.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Force this cell to recalculate any time any cell is selected/highlighted
Range("A1").Calculate
End Sub
Now anytime moves around on the worksheet Cell A1 will recalculate.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Range("A1:D4"), Target) Is Nothing Then
Range("A1:D4").Interior.Color = xlNone
Target.Interior.ColorIndex = 6
End If
End Sub
This will now highlight the cell chosen only if the cell chosen is in A1:D4

How to highlight active row in excel and then return to base background color in VBA

How do you highlight an active row in excel in VBA. and then when another row is selected, return that row to base background color, and highlight the new row.
Also how to clear all rows highlighted, using a clear button on the user form.
so there are tow question here, one to high light and unhighlight active rows, and the other to just clear all high lights by pressing a clear button on the form.
I know I can highlight a row using Ret.EntireRow.Interior.ColorIndex = 6 but i cant find code to unhighlight.
Thanks for your help.
You can use your 'clear all' functionality before changing the color of the row of the cell that you navigated to.
Open the VB Editor and right click --> view code on the worksheet that you want the row highlighting to take place.
Paste in this code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Me.Range("A1:XFD1048576").Interior.ColorIndex = 0
Target.EntireRow.Interior.ColorIndex = 6
End Sub
This code operates as follows: whenever a user changes his or her selected cell(s) on the sheet, the code will first clear the existing highlighting away in the entire sheet and then will apply new highlighting to the row of the target cell the user has moved to.
This line of code:
Worksheets("YourSheetName").Range("A1:XFD1048576").Interior.ColorIndex = 0
Will clear the colors from all cells in the worksheet.
You may want to limit the Range("A1:XFD1048576") to the usable range on your workbook as this will increase performance. On my machine I see a very subtle, but still noticeable, delay in the colors when I move the cells (because I am clearing all cells in the sheet instead of just the ones I want). If you do this, you probably wouldn't want to use the .EntireRow attribute, instead you would have to enumerate how far along the workbook you want the row to be highlighted.
Update
Try this code below, which eliminates the need to clear the entire worksheet. I used .ColorIndex=xlNone instead of setting it to 0 which should preserve your table formatting. I tested in Excel 2010 and I formatted some data as a table, it highlights the correct row and unhighlights the other row as well as leaving the table formatting in tact.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Static rr
If rr <> "" Then
With Rows(rr).Interior
.ColorIndex = xlNone
End With
End If
r = Selection.Row
rr = r
With Rows(r).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub
The trick is using Static. This allows the variable to continue to exist after termination of the procedure, so it remembers the last row it highlighted and then performs the un-highlight action accordingly.
The procedure first checks to see that rr is set, if it is not then it moves on, if it is then rr represents the row that was previously highlighted.
This can be done without changing the base background color,
In 2 steps,
Set up a conditional formatting rule that highlights an entire row if a certain formula is true.
In the formula field, enter this formula:
=OR(CELL("row")=CELL("row",A1))
Write a macro that recalculates the selected cell(s) when a new selection is made.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Target.Calculate
End Sub
Hit Alt + F11 to get back to Excel and you'll have the active cell's row highlighted with the format you chose, without changing the base colors of the cells.
For detailed explanation visit,
highlighted the entire row of the active cell.

Highlight active row/column in Excel without using VBA?

What I want to achieve is to highlight active row or column. I used VBA solutions but everytime Selection_change event is used I am loosing chance to undo any changes in my worksheet.
Is there a way to somehow highlight active row / column without using VBA?
The best you can get is using conditional Formatting.
Create two formula based rules:
=ROW()=CELL("row")
=COLUMN()=CELL("col")
As shown in:
The only drawback is that every time you select a cell you need to recalculate your sheet. (You can press "F9")
You can temporarily highlight the current row (without changing the selection) by pressing Shift+Space. Current column with Ctrl+Space.
Seems to work in Excel, Google Sheets, OpenOffice Calc, and Gnumeric (all the programs I tried it in).
(Thanks to https://productforums.google.com/forum/#!topic/docs/gJh1rLU9IRA for pointing this out)
Unfortunately, not as nice as the formula and macro-based solutions (which worked for me BTW), because the highlighting goes away upon moving the cursor, but it also doesn't require the hassle of setting it up each time, or making a template with it (which I couldn't get to work).
Also, I found you could simplify the conditional formatting formula (for Excel) from the other solutions into a single formula for a single rule as:
=OR(CELL("col")=COLUMN(),CELL("row")=ROW())
Trade off being that, if you did it this way, the highlighted column and row would have to use the same formatting, but that's probably more than adequate for most cases, and is less work.
(thanks to https://trumpexcel.com/highlight-active-row-column-excel/ for abbreviated formula)
I don't think it can be done without using VBA, but it can be done without losing your undo history:
In VBA, add the following to your worksheet object:
Public SelectedRow as Integer
Public SelectedCol as Integer
Private Sub Worksheet_SelectionChange(ByVal Target as Range)
SelectedRow = Target.Row
SelectedCol = Target.Column
Application.CalculateFull ''// this forces all formulas to update
End Sub
Create a new VBA module and add the following:
Public function HighlightSelection(ByVal Target as Range) as Boolean
HighlightSelection = (Target.Row = Sheet1.SelectedRow) Or _
(Target.Column = Sheet1.SelectedCol)
End Function
Finally, use conditional formatting to highlight cells based on the 'HighlightSelection' formula:
First of all Thanks! I had just created a solution with highlighting cells, using the Selection_Change and changing a cells content. I did not know it would disable Undo.
I found a way to do it by using combining conditional formatting, Cell() and the Selection_Change event. This is how I did it.
In Cell A1 I put the formula =Cell("row")
Row 2 is completely empty
Row 3 contains the headers
Row 4 and down is the data
To make the formula in A1 to be updated, the sheet need to recalculate. I can do that with F9, but I created the Selection_Change event with the only code to be executed is Range("A1").Calculate. This way it is done every time the user moves around, and as the Selection_Change is NOT changing any values/formats etc in the sheet, Undo is not disabled.
Now just enter the conditional formatting to highlight the cells that have the same row as cell A1.
Select the whole column B
Conditional Formatting, Manage Rules, New Rule, Use a Formula to determine which cells to format
Enter this formula: =Row(B1)=$A$1
Click Format and select how you want it to be highlighted
Ready. Press OK in the popups.
This works for me.
An alternative to Range.Calculate is using ActiveWindow.SmallScroll
The only downside is that the screen flickers for a split second after making a new selection.
While scrolling manually, you need to make sure the new selection moves out of the screen (window) completely, for it to work. Which is why, in below code, we need to scroll enough to get all visible rows out of the screen view and then scroll back to same position -to force screen refresh for conditional formatting.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ScreenUpdating = False
ActiveWindow.SmallScroll Down:=150 'change these values to total rows displayed on screen
ActiveWindow.SmallScroll Down:=-150 'change these values to total rows displayed on screen
'DoEvents 'unable to use this to remove the screen flicker
ScreenUpdating = True
End Sub
Credits:
Rory Archibald
https://www.experts-exchange.com/questions/28275889/When-is-excel-conditional-formatting-refreshed.html
Using conditional formatting, instead of highlighting the entire row and column, it is possible to highlight the row to the left of the cell and the column above the cell with the code below:
=OR(AND(CELL("col")=COLUMN();(CELL("row")-1)>=ROW());AND(CELL("col")>=COLUMN();(CELL("row")-1)=ROW()))
On the sheets Selection_change event call the following:
Function highlight_Row(rngTarget As Range)
Dim strRangeRow As String
strRangeRow = rngTarget.Row
strRangeRow = strRangeRow & ":" & strRangeRow
Rows(strRangeRow).Select
rngTarget.Activate
End Function
This is long format for clarity!
also add this code in vba to refresh sheet (instead of F9)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Application.CutCopyMode = False Then
Application.Calculate
End If
End Sub
to highlight the active column and row, up to the cell being clicked, without colouring the cell being clicked, and without colouring the entire column and row, this formula in Conditional Formatting works in Excel:
=OR(AND(CELL("col")=COLUMN(),(CELL("row")-1)>=ROW()),AND(CELL("row")=ROW(),(CELL("col")-1)>=COLUMN()))
Divide the number (to be formatted) by subtotal of itself in another column, which will cause error for hidden items and runtime conditional formatting with Graded Color Scale can be achieved.

Resources