Monday, October 6, 2008

A Good VBA tool for Excel Workers

Code Snippet:

Option Explicit
 
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    
    Dim RngRow          As Range
    Dim RngCol          As Range
    Dim RngFinal        As Range
    Dim Row             As Long
    Dim Col             As Long
    
    Cells.Interior.ColorIndex = xlNone
    
    Row = Target.Row
    Col = Target.Column
    
    Set RngRow = Range("A" & Row, Target)
    Set RngCol = Range(Cells(1, Col), Target)
    Set RngFinal = Union(RngRow, RngCol)
    
    RngFinal.Interior.ColorIndex = 6
    
End Sub

How to use?

   1. Open Excel.
   2. Press Alt+F11 to open the VBE.
   3. From the Project Explorer double click on one of the Sheets (i.e. Sheet1).
   4. Paste the code in the window that opens up.
   5. Close the VBE (Alt + Q or press the X in the top-right corner).

Testing:

   1. In Excel goto the sheet you put the code in.
   2. Select a cell and see the area get highlighted.
   3. Note that with this macro as is, all other cell fill colors will be removed.

Enjoy scripting with VBA !!!


No comments: