View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default Problem with Subs and If's !

If your code changes something on the worksheet, then that worksheet_change
event is fired again (and again and again...)

So tell excel to stop looking for changes:

Private Sub Worksheet_Change(ByVal Target As Range)
Application.enableevents = false
If Target.Value = "GD" Then
Selection.Range("B1").Value = "Graeme John Dixon"
Else
Selection.Range("B1").Value = "I don't know you"
End If
application.enableevents = true
End Sub

I'd add a few checks, too:

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Cells.Count 1 Then Exit Sub

'if you want to only check in a specific range:
If Intersect(Target, Me.Range("a:a")) Is Nothing Then
Exit Sub
End If

On Error GoTo ErrHandler:

Application.EnableEvents = False
If LCase(Target.Value) = LCase("GD") Then
Target.Offset(0, 1).Value = "Graeme John Dixon"
Else
Target.Offset(0, 1).Value = "I don't know you"
End If

ErrHandler:
Application.EnableEvents = True
End Sub



Tachyon wrote:

Hi - Ok, I'm a real newbie so this will be easy for someone :-)

I can't figure why this code loops around in strange ways and doesn't just
step through doing the If's and Then's etc. I'll say no more at this stage
because it's probably embarassingly blindingly obvious to everyone else!

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Value = "GD" Then
Selection.Range("B1").Value = ("Graeme John Dixon")
Else
Selection.Range("B1").Value = ("I don't know you")
End If
If Range("B5").Value = ("Graeme John Dixon") Then
Range("A1") = ("Test")
End If
End Sub

--
Tachyon


--

Dave Peterson