Excel: Change the background color of a cell when another cell is selected


Question:  I'm looking for VBA code that will change the background color of a cell when I click on another cell.


For example, if I click on cell A1, I'd like the background color of cell B2 to change to red.


Answer:  To change the background color of a cell A1 when cell B2 is clicked, we need to create a macro that is called when the Worksheet's SelectionChange event is fired.


Download Excel spreadsheet (as demonstrated below)


In the spreadsheet below, we've created a macro that will run each time the user selects a different cell on Sheet1.




If the user selects cell A1, the macro will set the background color of cell B2 to red.




You can view the macro by pressing Alt-F11.


Macro Code:

The macro code looks like this:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)


    If Not Intersect(Range("A1"), Target) Is Nothing Then
        Range("B1").Interior.ColorIndex = 3
        Range("B1").Interior.Pattern = xlSolid
    End If

End Sub

Spreadsheet News


Book Shop


Visit our busy book shop, were you can find latest books for beginners as well as advanced excel users.



Software Library




Spreadsheet123

Spreadsheet 123 Spreadsheet Software Development

Home | About Us | Our Services | Software | Spreadsheets Library | Excel Tutorials | Useful Links | Site Map | Contact Us
Home
About Us
About Spreadsheet
Book Shop
Excel Tutorials
1
Spreadsheets Library
3
4
5
6
Our Services
8
Site Map
Software
11
12
13
14
15
16
17