Too much coffee this morning......
To avoid running a macro manually each time a change is made to a cell's
colour, the code below will execute each time you select a new cell.
Depending upon the size of your workbook, this may impair performance.
Save the code to the relevant "Worksheet" module, not a general module.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim r As Range, c As Range, rr As Range
'Amend sheet name as necessary
Set r = Sheets("Sheet1").UsedRange
Application.Calculation = xlCalculationManual
For Each c In r
If c.Interior.ColorIndex = 2 Then
If rr Is Nothing Then
Set rr = c
Else
Set rr = Union(rr, c)
End If
End If
Next c
If Not rr Is Nothing Then
'Amend sheet name as necessary
With Sheets("Sheet1")
ThisWorkbook.Names.Add Name:="Background", RefersTo:=rr
End With
End If
Application.Calculation = xlCalculationAutomatic
End Sub
--
XL2002
Regards
William
[email protected]
| Here is the revised code so that the range is NOT selected.
|
| Sub RangeBasedUponColor()
| Dim r As Range, c As Range, rr As Range
| Set r = ActiveSheet.UsedRange
| For Each c In r
| If c.Interior.ColorIndex = 2 Then
| If rr Is Nothing Then
| Set rr = c
| Else
| Set rr = Union(rr, c)
| End If
| End If
| Next c
| If Not rr Is Nothing Then
| With ActiveSheet
| ThisWorkbook.Names.Add Name:="Background", RefersTo:=rr
| End With
| End If
| End Sub
|
| --
| XL2002
| Regards
|
| William
|
|
[email protected]
|
| | | Thanks for your quick response!!! That is almost it... First I had to
| | edit it to make it work, look below at the line in red; I had to change
| | it to: Range("Background").Select (I removed the two periods).
| |
| | Sub RangeBasedUponColor()
| | Dim r As Range, c As Range, rr As Range
| | Set r = ActiveSheet.UsedRange
| | For Each c In r
| | If c.Interior.ColorIndex = 2 Then
| | If rr Is Nothing Then
| | Set rr = c
| | Else
| | Set rr = Union(rr, c)
| | End If
| | End If
| | Next c
| | If Not rr Is Nothing Then
| | With ActiveSheet
| | ThisWorkbook.Names.Add Name:="Background", RefersTo:=rr
| | .Range("Background").Select
| | End With
| | End If
| | End Sub
| |
| | I kept getting an error until I did that. Now it works but only if I
| | run it like a macro, is it possible to have it run so if a change is
| | made it will catch it without having to run the macro again? If that
| | is not possible then I guess I could just have the macro run everytime
| | the file is opened.
| |
| | Second, is there a way to keep from selecting the cells, I just want it
| | to define a name not really select the cells.
| |
| | Thanks again for your help and quick reply.
| |
| |
| | ---
| |
| |
|
|