Use a shape to highlight the selection.
Note: It works only when switching to another Excel window. As a workaround you can open an empty Excel window and switch to this window before switching to another application to keep the highlight.
Just add this to your ThisWorkbookcode (your workBOOK, not your sheet´s code).
This will work for every sheet in your workbook.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
DeleteSelectionHighlight
End Sub
Private Sub Workbook_WindowActivate(ByVal Wn As Window)
DeleteSelectionHighlight
End Sub
Private Sub Workbook_WindowDeactivate(ByVal Wn As Window)
On Error Resume Next
Dim shp As Shape
Application.ScreenUpdating = False
Set shp = ActiveSheet.Shapes("SelectionHighlight")
If Err.Number <> 0 Then
Set shp = ActiveSheet.Shapes.AddShape(msoShapeRectangle, 1, 1, 1, 1)
With shp 'Format shape to your preference
.Name = "SelectionHighlight"
.Line.ForeColor.RGB = RGB(226, 0, 0) ' Border color
.Line.Weight = 1.5
.Line.DashStyle = msoLineSolid
.Fill.Visible = msoFalse 'No background
'.Fill.ForeColor.RGB = RGB(0, 153, 0) 'Background color
'.Fill.Transparency = 0.95 'Background transparency
End With
End If
Dim oldZoom As Integer
oldZoom = Wn.Zoom
Wn.Zoom = 100 'Set zoom at 100% to avoid positioning errors
With shp
.Top = Wn.Selection.Top 'Tweak the offset to fit your desired line weight
.Left = Wn.Selection.Left 'Tweak the offset to fit your desired line weight
.Height = Wn.Selection.Height
.Width = Wn.Selection.Width
End With
Wn.Zoom = oldZoom 'Restore previous zoom
Application.ScreenUpdating = True
End Sub
Private Sub DeleteSelectionHighlight()
On Error Resume Next
Dim shp As Shape
Set shp = ActiveSheet.Shapes("SelectionHighlight")
shp.Delete
End Sub
You can even format the shape to your preference by tweaking the code.
The advantages are:
- you don´t lose your original formatting when excel crashes of you have a power failure
- You don´t lose your original formatting when using CTRL+[ from another workbook that changes the active sheet
- You don´t lose the highlight when making changes to the other excel window while compared to the CTRL+C solution