How to highlight row when click and apply code to all tabs in Excel - excel

I want for a row to be highlighted when clicked and remove the highlight of that row when another one is clicked.
For this, I've found a code here to do it in a particular tab. I what to apply it to all the tabs. Therefore I've added the following code in 'ThisWorkbook':
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Static xRow
If xRow <> "" Then
With Rows(xRow).Interior
.ColorIndex = xlNone
End With
End If
pRow = Selection.Row
xRow = pRow
With Rows(pRow).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub
With this code the row gets highlighted when a value of that row is changed, but not when clicked. Is there any way to achieve to highlight when clicked for all tabs?

This works for me. It uses Worksheet_SelectionChange instead of Worksheet_SheetChange. Only current cell gets highlighted. I've added it into a sheet code window. When you paste the code directly to "ThisWorkbook" code window then it works for all Sheets.
Option Explicit
Dim PreviousCell As Range
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not PreviousCell Is Nothing Then
Dim xRow As Variant, prow As Variant
prow = Selection.Row
xRow = prow
If Not PreviousCell Is Nothing Then
With Rows(PreviousCell.Row).Interior
.ColorIndex = xlNone
.Pattern = xlNone
End With
End If
With Rows(xRow).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End If
Set PreviousCell = Target
End Sub
To paste the code into ThisWorkbook select the object at top above the code window > choose "Workbook" and then select the procedure > select "SheetSelectionChange".
Now copy/paste the code between
Private ..... End sub
When you click inside the Sub and it look like this ( (General) ) it's not working:
This is working:
This will not work:
Idea came from this answer:
Excel VBA: Get range of previous cell after calling LostFocus()

Related

Highlight surrounding cells of selected cell

I am trying to exercise Levenshtein Distance in Excel. To fill the cells, we need to consider the minimum of three cells (left, up-left, and up). It is easy to find minimum of those three if they were highlighted.
I want to highlight those three cells whenever I put my cursor on any empty cell. Just like shown on image below. When I put my cursor on C3; B2, B3, and C2 should be higlighted.
I found a VBA script. But it higlightes the entire row and column of cursor cell. I am not familiar with VBA, therefore can't modify rows and columns to my way.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
'Update 20200430
Static xRow
Static xColumn
If xColumn <> "" Then
With Columns(xColumn).Interior
.ColorIndex = xlNone
End With
With Rows(xRow).Interior
.ColorIndex = xlNone
End With
End If
pRow = Selection.Row
pColumn = Selection.Column
xRow = pRow
xColumn = pColumn
With Columns(pColumn).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
With Rows(pRow).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub
this is what it does
A Worksheet SelectionChange: Highlight Cells
Sub Worksheet_SelectionChange(ByVal Target As Range)
With Target.Cells(1)
If .Row = 1 Then Exit Sub
If .Column = 1 Then Exit Sub
If IsEmpty(.Cells) Then
.Worksheet.UsedRange.Interior.ColorIndex = xlNone
Union(.Offset(-1, -1).Resize(2), .Offset(-1)) _
.Interior.Color = vbYellow
End If
End With
End Sub

Remove Cell color when cell color is created with a Macro Code

I created a Macro to change a cell to yellow when a change is made (top Macro). I now want to create a code so I can create a button to click to remove all of the yellow that was created with the top Macro.
I was able to find the bottom code which does turn manually highlighted cells from yellow back to white but not cells turned yellow from my Top Macro.
Below are the formats I used:
To create the Yellow Color when a change is made:
'Highlight cells yellow if change occurs
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
Target.Interior.ColorIndex = 6
End Sub
To Remove Yellow Highlight (only works for Manual change- not the Macro)
Sub RemoveYellowFillColor()
Dim cell As Range
'Optimize Code
Application.ScreenUpdating = False
'Ensure Cell Range Is Selected
If TypeName(Selection) <> "Range" Then
MsgBox ("A2:Z1000")
Exit Sub
End If
'Loop Through Each Cell
For Each cell In Selection.Cells
If cell.Interior.Color = vbYellow Then
cell.Interior.Color = xlNone
End If
Next
End Sub
This is Rev. 1 of my answer:
As noted in comments, change from Target.Interior.ColorIndex = 6 to Target.Interior.ColorIndex = vbYellow in Workbook_SheetChange.
Then update your macro as follows:
Sub RemoveYellowFillColor()
Dim ws As Worksheet, cell As Range
'Optimize Code
Application.ScreenUpdating = False
'Loop Through Each Cell
For Each ws In Worksheets
For Each cell In ws.UsedRange.Cells
If cell.Interior.Color = vbYellow Then cell.Interior.Color = xlNone
Next cell
Next ws
Application.ScreenUpdating = True
End Sub
After running this macro, vbYellow fill will be removed from all cells on all worksheets in the workbook.

Application.Goto Target Cell Not in View

I have created a simple Excel Macro which is triggered when a user clicks on a cell in a worksheet (worksheet1). Basically the macro takes the value of the cell which was clicked on and selects a target cell in a separate worksheet (worksheet2) that has the same value.
The problem is that about 20% of the time after being directed to worksheet2, the target cell is highlighted but is just out of view, i have to scroll down a couple of rows to see it. I want to be able to ensure that the target cell is always in view after the user is directed to it, but I am not sure how this can be achieved.
This is in Excel 2016.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If ActiveCell.Column = 1 Then
If Target.Cells.Count = 1 Then
Application.ScreenUpdating = False
Dim c As Range
Dim ans As String
Dim Lastrow As Long
ans = ActiveCell.Value
Lastrow = Sheets("worksheet2").Cells(Rows.Count, "A").End(xlUp).Row
For Each c In Sheets("worksheet2").Range("A2:A" & Lastrow)
If c.Value = ans Then Application.Goto Reference:=Sheets("worksheet2").Range(c.Address): Exit Sub
Next
End If
End If
Exit Sub
End Sub
You can use find to find the selected item in sheet2 then just select the sheet and the found cell
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim s As Range
If Target.Column = 1 Then
Set s = Worksheets("Sheet2").Range("B:B").Find(what:=Target, lookat:=xlWhole)
If Not s Is Nothing Then
Worksheets("Sheet2").Activate
s.Select
Else: MsgBox Target.Value & " is not found in sheet 2"
End If
End If
End Sub

Highlight cell rows on selection error

I have this code for my Excel worksheet. It highlights the table rows by the row you have selected but problems arise if you highlight cells in the table to the outside or you put a slicer in the table. Here it the Module I use:
Option Explicit
Public Sub HighlightTableRow(Target As Excel.Range)
Dim t As ListObject
Dim lngInTable As Long
Dim c As Long
Const COLOR_SELECT = xlThemeColorAccent1
Const COLOR_LIGHTER = 0.4
On Error Resume Next
If Target.Interior.Pattern = xlPatternSolid Then Exit Sub
For Each t In Target.Parent.ListObjects
c = c + 1
If Not Intersect(Target, t.DataBodyRange) Is Nothing Then
lngInTable = c
End If
t.Range.Interior.Pattern = xlNone
Next
If lngInTable = 0 Then Exit Sub
With Target.Parent.ListObjects(lngInTable)
With .Range.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With .DataBodyRange
With .Resize(Target.Rows.Count).Offset(Target.Row - .Row).Interior
.ThemeColor = COLOR_SELECT
.TintAndShade = 1 - COLOR_LIGHTER
End With
End With
End With
End Sub
And I put this code in each Excel sheet so the code works:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
HighlightTableRow Target
End Sub
I have no idea how to fix this error. The formatting gets weird. Any ideas?

Color cells with specific data

I have a macro to color cells that have the word VOID in it.
I also have the word VOID in a cell like this: [$189.00VOID].
I can't find a way to color all cells that contain:
VOID and [$189.00VOID]
or any other dollar amount in it.
Sub Macro1()
On Error Resume Next
Dim current As String
For i = 1 To 65536 ' go from first cell to last
current = "c" & i ' cell counter
Range(current).Select ' visit the current cell
If Range(current).Text = "VOID" Then ' if it says VOID then we...
With Selection.Interior
.ColorIndex = 3 ' ...go red
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End If
If Range(current).Text = "FORWARDED" Then ' if it says FORWARDED then we...
With Selection.Interior
.ColorIndex = 4 ' ...go green
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End If
Next i ' loop and check the next cell
End Sub
VBA really seems like overkill for this. As pnuts said, conditional formatting will do everything you need.
Select the cell(s) you want to format, then Home Ribbon -> Conditional Formatting -> New Rule -> Format Only Cells that Contain
Then change the first combo box from Cell Value to specific text. and in the empty text box on the right type VOID.
You can then adjust the cell formatting to be whatever you want.
For something like this, I would really recommend using conditional formatting (as has already been stated). Here are the two Condtional Format formulas that you would need to apply to column C:
=COUNTIF($C1,"*VOID*")>0
=COUNTIF($C1,"*FORWARDED*")>0
However, if it absolutely has to be VBA, then right-click the sheet tab that you want to monitor and select "View Code". In there, paste the following:
Private Sub Worksheet_Calculate()
Dim rngColor As Range
Dim rngFound As Range
Dim strFirst As String
Dim varFind As Variant
'Remove current formatting (if any)
Columns("C").Interior.Color = xlNone
'Check for both VOID and FORWARDED
For Each varFind In Array("VOID", "FORWARDED")
'Attempt to find a cell that contains varFind
Set rngFound = Columns("C").Find(varFind, Me.Cells(Me.Rows.Count, "C"), xlValues, xlPart)
'Check if any cells were found
If Not rngFound Is Nothing Then
'The first cell was found, record its address and start rngColor
strFirst = rngFound.Address
Set rngColor = rngFound
'Begin loop
Do
'Add found cell to rngColor
Set rngColor = Union(rngColor, rngFound)
'Advance loop by finding the next cell
Set rngFound = Columns("C").Find(varFind, rngFound, xlValues, xlPart)
'Exit loop when back to first cell
Loop While rngFound.Address <> strFirst
'Fill rngColor based on varFind
Select Case varFind
Case "VOID": rngColor.Interior.Color = vbRed
Case "FORWARDED": rngColor.Interior.Color = vbGreen
End Select
End If
Next varFind
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Worksheet_Calculate
End Sub

Resources