VBA Tweak

dantheram

Board Regular
Joined
Aug 27, 2010
Messages
192
Office Version
  1. 365
Platform
  1. Windows
Evening,

how do I stop the below code applying to the entire sheet, i wish for it to only take affect on a set range, in this instance g2:g35

Code:
  Private Sub Worksheet_SelectionChange(ByVal Target As Range)    'Task1: Show your active cell contents in cell E2
    actval = ActiveCell.Value
    actaddr = ActiveCell.Address
    Range("E2") = actval


    'Task2: Turn selected cell red


    'first set entire background white
    Range("g2:g35").Interior.Color = xlNone
    ActiveCell.Interior.ColorIndex = 3
   End Sub
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
You should be referring to Target not Activecell, this is the range that is passed to the SelectionChange event. I also put in a check to see that only 1 cell was selected since you are writing the value to E2.

Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Range("G2:G35"), Target) Is Nothing Then
    Range("E2") = Target
    Range("G2:G35").Interior.Color = xlNone
    Target.Interior.Color = vbRed
End If
End Sub
 
Last edited:
Upvote 0
You should be referring to Target not Activecell, this is the range that is passed to the SelectionChange event. I also put in a check to see that only 1 cell was selected since you are writing the value to E2.

Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Range("G2:G35"), Target) Is Nothing Then
    Range("E2") = Target
    Range("G2:G35").Interior.Color = xlNone
    Target.Interior.Color = vbRed
End If
End Sub

Perfect!

thanks
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,022
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top