Excel - Force recalculation when different cell is selected - excel

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

Related

Excel selecting a number of cells below selected cell shortcut options

In Excel, I would like to select a cell and then copy the contents to n number of cells below. Instead of using the "fill" drag option since the number of rows will be fairly large and require scrolling and then stopping at the correct cell I was looking for other options.
I am currently doing the the following:
In excel I select a cell and then on the top left corner it shows the cell (i.e. A1). Then to select the number of cells below it, I modify the top left box to a range such as A1:A10 which selects the range of cells. See attached image. I then use the shortcut key "Ctrl-D" which copies the first cell to the other cells.
Is there a way instead of mentally calculating the ending cell number, I can do something that effectively works "A1 + 10" in this box to select 10 cells below to select the A1:A10 range?
How about this way? Enter your formula in cell 1. Enter the number of copies (including the original) you want of it in the cell below it. Double-click on the number you entered and the formula is filled down.
To try, install the procedure below in the code module of the worksheet on which you want the action. (That's a module Excel set up when you created the sheet. Don't install the code in a standard code module that you have to insert yourself.)
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Const TriggerClm As String = "A"
Dim R As Long
With Target
If (.Column = Columns(TriggerClm).Column) And (.Row > 1) Then
R = Val(.Value)
If R Then
With .Offset(-1)
If .HasFormula Then
.Resize(R).FillDown
.Select
Cancel = True
End If
End With
End If
End If
End With
End Sub
You may wish or have to tweak the code. For example, the action is limited to column A. Change the constant at the top of the code to identify the column you prefer, or change the limits to better suit your requirements. The code also checks if Cell #1 contains a formula. If that isn't what you want to fill down that condition will have to be revised.
Last, but not least, the code selects Cell#1 (the one that contained the number is over-written). That may not be the best choice. You can modify the code to select a place in your worksheet where you will continue working.

Record Changing Cell Value in Excel

I have a cell whose value is constantly changing through a feed. I want to develop a macro which when activated records the cell value at that instant and pastes it in another cell. Tried finding some formula to do that but no success.
You won't be able to do that with a formula. However, you can write a macro that checks if your cell was changed:
Private Sub Worksheet_Change(ByVal Target As Range)
...
End Sub
If you don't want this type of automation, you could simply add a button to your worksheet which triggers a macro when clicked and does what you are looking for.
To copy the value of a cell into another one, you could use this simple solution:
Range("B1").Value = Range("A1").Value
This will copy the value of cell A1 into cell B1.

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.

Excel formula refer to cell to the right, in frozen pane

I can usually find all the answers I need through Google searches. This one has me stumped; maybe it isn't possible.
My sheet is set up with B5 as its first unfrozen cell. How can I enter a formula in cell A3 that refers to the first cell that is currently showing in the top right pane? So in the worksheet's initial state, A3 would refer to B3, but if I scrolled right 10 rows, for instance, A3 would then refer to K3.
Excel uses cell references in formulas. A cell reference does not change when you scroll. You would need VBA to determine the top left cell of a pane. This cell value can be written into a helper cell and you could reference that helper cell in the formula in the frozen pane.
The VBA would run as a Selection Change event, i.e. when the user clicks in a different cell or uses the keyboard to navigate. It would not work for scrolling with the mouse wheel, since that is not an event in the Excel object model. (Chip Pearson has some code for that, though, here).
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim i As Integer, pane As Integer
Dim PaneTop As String
pane = ActiveWindow.Panes.Count
PaneTop = ActiveWindow.Panes(pane).VisibleRange.Address
i = InStr(PaneTop, ":")
PaneTop = Left(PaneTop, i - 1)
Range("A3").Formula = "=" & PaneTop
End Sub
This function puts a cell reference to the top left cell of the pane into A3. Change it to include your formula, or write it to a different cell and let your formula refer to that 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