Highlight cell rows on selection error - excel

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?

Related

Highlight Selected Row & Columns

I have this code which is below. The highlight is always enable. I am trying to find out how can i create something to enable/disable whenever i want.
Thanks in advance.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
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
Try,
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Cells.Interior.Color = xlNone
If Range("a1") = "" Then Exit Sub 'Set operation according to a1 cell
With Target
.EntireRow.Interior.ColorIndex = 6
.EntireColumn.Interior.ColorIndex = 6
End With
End Sub
It would be nice to insert the activeX control Checkbox in the sheet and set the behavior accordingly.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Cells.Interior.Color = xlNone
'If Range("a1") = "" Then Exit Sub
If CheckBox1 Then Exit Sub
With Target
.EntireRow.Interior.ColorIndex = 6
.EntireColumn.Interior.ColorIndex = 6
End With
End Sub

How to highlight row when click and apply code to all tabs in 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()

Executing the VBA code on opening the excel instead of Changing value

I have a VBA code for a Rota Sheet that is activated on change of any value in the row.
I want the code to be activated upon opening the excel.
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Range("B2:V11")
If Not Intersect(Target, rng) Is Nothing Then
'scan each row (month)
Dim countRow As Long
Dim i As Long
For i = 1 To rng.Rows.count
If Not Intersect(Target, rng.Rows(i)) Is Nothing Then
If WorksheetFunction.CountIf(rng.Rows(i), "V") > 0 Then
countRow = 0
Dim cel As Range
For Each cel In rng.Rows(i).Cells
If cel.Value2 = "V" Then
countRow = countRow + 1
VacationChange cel, countRow
Else
VacationChange cel, 0
End If
Next cel
End If
End If
Next i
'scan each column (day)
Dim j As Long
For j = 1 To rng.Columns.count
If Not Intersect(Target, rng.Columns(j)) Is Nothing Then
If WorksheetFunction.CountIf(rng.Columns(j), "V") > 5 Then
VacationChange rng.Columns(j).Cells(0, 1), 6
Else
VacationChange rng.Columns(j).Cells(0, 1), 0
End If
End If
Next j
End If
End Sub
Private Function VacationChange(ByVal rng As Range, ByVal count As Long)
With rng.Interior
Select Case count
Case 0
'clear cell colors
.Pattern = xlNone
.Color = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
Case 1 To 3
'blue
.Pattern = xlSolid
.Color = 15773696
.TintAndShade = 0
.PatternTintAndShade = 0
Case 4 To 5
'yellow
.Pattern = xlSolid
.ThemeColor = xlThemeColorAccent4
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
Case Else
'red
.Pattern = xlSolid
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End Select
End With
End Function
I spent efforts by trying:
1. Using below code in Workbook: which is throwing 424 error
Private Sub Workbook_Open()
Sheet1.Activate
Call Worksheet_Change(Target)
End Sub
Pasting the entire code under Workbook_Open() function which is not working
Can anyone suggest what i am missing in the code ?
Sample Output image is attached
enter image description here
The problem is that Target is an undeclared Variant in your Workbook_Open implementation. That means when it gets passed as a parameter that needs to be a Range, the implicit cast fails and results in an error 424 (Object required).
If you want to "simulate" every cell in your target range changing, you can simply loop over B2:V11 and pass it each individual cell (untested with your data, but should give the gist):
Private Sub Workbook_Open()
Sheet1.Activate
Dim cell As Range
For Each cell In Sheet1.Range("B2:V11")
'Worksheet_Change needs to be Public
Sheet1.Worksheet_Change cell
Next
End Sub
Note that this is by no means the ideal solution to what you are trying to do and is a sign that you need to refactor your code a little bit to extract the functionality that you currently have in Worksheet_Change into a free-standing procedure. If you need to run the same code from the Worksheet_Change handler, you can call that procedure.

Avoid highlighting rows that are not intended to

I have the following code to highlight in green the row which the user clicks.
In the end of the code, I select the cell B6 to deselect the whole row and move the selection above.
It is working fine except for the fact that cell B6 is also being highlighted in green and I do not want that. How can I remove that?
In the worksheet I have:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'If not in the table, exit sub
If Intersect(Range("Schema"), ActiveCell.EntireRow) Is Nothing Then Exit Sub
Call ClickInside
End Sub
And in the module:
Sub ClickInside()
Dim cellno As String: cellno = Str(ActiveCell.row)
Dim myRow As Range
Set myRow = ActiveCell.EntireRow 'I want to select the row in the table ONLY
Call Unprotect_table
Call MarkRow(cellno, myRow)
Call Protect_table
End Sub
Sub MarkRow(cellno As String, myRow As Range)
'Marking that row in green
Range("Schema").Interior.ColorIndex = 0
Range("B" & Trim(cellno) & ":I" & Trim(cellno)).Select
With Selection.Interior
.PatternColorIndex = xlAutomatic
.Color = RGB(0, 255, 0)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Application.ScreenUpdating = False
'Show above
If Not myRow Is Nothing And CLng(cellno) >= 9 Then
Range("EditCountry").Value2 = ThisWorkbook.ActiveSheet.Range("B" & Trim(cellno)).Value2
Range("EditNodeName").Value2 = ThisWorkbook.ActiveSheet.Range("C" & Trim(cellno)).Value2
Range("EditNodeId").Value = ThisWorkbook.ActiveSheet.Range("D" & Trim(cellno)).Value2
Range("EditParentNode").Value = ThisWorkbook.ActiveSheet.Range("E" & Trim(cellno)).Value2
Range("EditParentNodeId").Value = ThisWorkbook.ActiveSheet.Range("F" & Trim(cellno)).Value2
Range("EditActive").Value = ThisWorkbook.ActiveSheet.Range("G" & Trim(cellno)).Value2
Range("EditFrom").Value = ThisWorkbook.ActiveSheet.Range("H" & Trim(cellno)).Value2
Range("EditTo").Value = ThisWorkbook.ActiveSheet.Range("I" & Trim(cellno)).Value2
End If
'Move selection
Range("B6").Select
End Sub
Thanks!
Your statement Range("B6").Select triggers the event-routine a second time. To prevent this, use the statement Application.EnableEvents = False:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Intersect(Range("Schema"), ActiveCell.EntireRow) Is Nothing Then Exit Sub
Application.EnableEvents = False
Call ClickInside
Application.EnableEvents = True
End Sub
However, maybe you could have a look to other solution that uses conditional formatting, for example https://stackoverflow.com/a/22350417/7599798

Unwanted Insert Row Infinite Loop

For some reason when i use the insert line code, it keeps on inserting a new row forever! I wrote the code that at the beginning there is a do while loop that goes through all the cells in column C, when it hits a cell in column C that is empty then an variable keeps the cell number.
and then i wrote another subroutine (which gets called when something changes on the spreadsheet) that if something is written in that empty cell in column C, then insert new row. but it just keeps on going forever!
The following code is under a module
Dim a, count As Integer
Sub check()
a = 0
count = 3
Do While a = 0
count = count + 1
If Range("C" & count).Value = "" Then
a = 1
End If
Loop
End Sub
Sub addrow()
If Range("C" & count).Value <> "" Then
Range("C" & count).Offset(1).EntireRow.Insert
count = count + 1
With Range("B" & count, "AL" & count)
.Borders(xlEdgeLeft).LineStyle = xlContinuous
.Borders(xlEdgeRight).LineStyle = xlContinuous
.Borders(xlEdgeBottom).LineStyle = xlContinuous
.Borders(xlEdgeTop).LineStyle = xlContinuous
.Borders(xlInsideVertical).LineStyle = xlContinuous
End With
End If
End Sub
And this code is under the worksheet
Private Sub Worksheet_Change(ByVal Target As Range)
addrow
End Sub
and subroutine "CHECK" is being called when the workbook is opened.
I have no idea why there is an infinite loop! please help.
Thank you
Just sandwich your Worksheet_Change event with Application.EnableEvents=False/True:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
addrow
Application.EnableEvents = True
End Sub
The reason is simple - when Worksheet_Change event inserts new row, it changes the content of the sheet, triggering Worksheet_Change event again. Worksheet_Change event insert new row again, and so on. Infinity loop:)
Btw, the best practice is to use error handling (it sets back Application.EnableEvents = True even if error occurs in addrow subroutine):
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo ErrorHandler
Application.EnableEvents = False
addrow
ExitHere:
Application.EnableEvents = True
Exit Sub
ErrorHandler:
Resume ExitHere
End Sub

Resources