an interesting Excel question

J

jaccker

I have a question about the using of Excel and VBA.

Let’s say in cell A1 and A2, I input 1 and 2. Then I input formul
“=SUM(A1+A2)” into cell A3.

I would like to write a VBA code to have the following functionality:

Once I change the formula in A3, let’s say I input 4 to cell A3, th
color of the cell A3 should be changed.
Once I double click the changed cell A3, it should recover to th
formula “=SUM(A1+A2)”.

Anybody could help me out to solve the problem?

Thank yo
 
B

Bob Phillips

This might work for you

Dim prevVal
Const WS_RANGE As String = "A3"

'-----------------------------------------------------------------
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As
Boolean)
'-----------------------------------------------------------------
If Not Intersect(Target, Me.Range(WS_RANGE)) Is Nothing Then
With Target
If .Interior.ColorIndex = 3 Then
.Formula = prevVal
.Interior.ColorIndex = xlColorIndexNone
End If
End With
End If

End Sub

'-----------------------------------------------------------------
Private Sub Worksheet_Change(ByVal Target As Range)
'-----------------------------------------------------------------

On Error GoTo ws_exit:
Application.EnableEvents = False
If Not Intersect(Target, Me.Range(WS_RANGE)) Is Nothing Then
With Target
.Interior.ColorIndex = 3 'red
End With
End If

ws_exit:
Application.EnableEvents = True
End Sub

'-----------------------------------------------------------------
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'-----------------------------------------------------------------
If Not Intersect(Target, Me.Range(WS_RANGE)) Is Nothing Then
With Target
If .HasFormula Then
prevVal = .Formula
End If
End With
End If
End Sub

'This is worksheet event code, which means that it needs to be
'placed in the appropriate worksheet code module, not a standard
'code module. To do this, right-click on the sheet tab, select
'the View Code option from the menu, and paste the code in.





--
HTH

Bob Phillips

(remove nothere from email address if mailing direct)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top