Hi,
Wish to colour fill my current cell within active table.
Manged to do it via this code. But how do I automatically get this to work in any workbook/any active table? Also the current code removes existing colour fill both within the table and outside of the table. Is there a way to preserve exisitng colour fill once current cell is de-selected.
Many Thanks
gareth
Wish to colour fill my current cell within active table.
Manged to do it via this code. But how do I automatically get this to work in any workbook/any active table? Also the current code removes existing colour fill both within the table and outside of the table. Is there a way to preserve exisitng colour fill once current cell is de-selected.
Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
Dim tbl As ListObject
Dim tblRange As Range
Dim tblHeader As Range
' Check if the selected cell is within a table
Set tbl = Nothing
Set tbl = ActiveSheet.ListObjects(Target.ListObject.Name)
' If a table is found, get the table range and header range
If Not tbl Is Nothing Then
Set tblRange = tbl.DataBodyRange
Set tblHeader = tbl.HeaderRowRange
' Clear formatting in the entire worksheet
Cells.Interior.ColorIndex = xlColorIndexNone
' Check if the selected cell is within the table range
If Not Intersect(Target, tblRange) Is Nothing Then
' Get the entire column of the active cell
Dim targetColumnIndex As Long
targetColumnIndex = Target.Column - tblRange.Columns(1).Column + 1
' Check if the target column index is within the valid range of the table
If targetColumnIndex >= 1 And targetColumnIndex <= tbl.ListColumns.Count Then
' Apply formatting to the active column within the table
On Error Resume Next
tbl.ListColumns(targetColumnIndex).DataBodyRange.Interior.ColorIndex = 37
tbl.ListRows(Target.Row - tblRange.Rows(1).Row + 1).Range.Resize(, tbl.ListColumns.Count).Interior.ColorIndex = 37
tblHeader.Columns(targetColumnIndex).Interior.Color = RGB(255, 165, 0)
On Error GoTo 0
' Clear formatting for the active cell
Target.Interior.ColorIndex = xlColorIndexNone
End If
End If
End If
' Clear formatting if the selected cell is outside the table range
If tbl Is Nothing Or Intersect(Target, tblRange) Is Nothing Then
Cells.Interior.ColorIndex = xlColorIndexNone
End If
On Error GoTo 0
End Sub
Many Thanks
gareth