I am trying to have 2 Worksheet_Change Events on one worksheet that are being triggered seperatly.
For example if I write in "C3" a Number a vlookup is either giving back a name or jumping to OnError GoTo NoSupplier, if i write in "C9" an other vlookup is either giving back a name or jumping to On Error GoTo NoCOMS.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim suppname As String
Dim COMS As String
If Target.Address(0, 0) = "C3" Then
If Target <> "" Then
On Error GoTo NoSupp
suppname = Application.VLookup(Target.Value, Workbooks("Articlepassport.xlsm") _
.Sheets("Suppliernames").Range("A2:B1000"), 2, False)
Range("C5") = suppname
Else
Range("C5") = ""
End If
Exit Sub
NoSupp: Range("C5") = "Supplier Data not maintained!"
End If
If Target.Address(0, 0) = "C9" Then
If Target <> "" Then
On Error GoTo NoCOMS
COMS = Application.VLookup(Target.Value, Workbooks("Articlepassport.xlsm") _
.Sheets("Tabelle2").Range("A2:B11000"), 2, False)
Range("C11") = COMS
Else
Range("C11") = ""
End If
Exit Sub
NoCOMS: Range("C11") = "COMS does not exist!"
End If
End Sub
You need to add Application.EnableEvents = False
so the Sub won't be triggerred multiple times. Before leaving the Sub
, you need to restore the settings to the original value with Application.EnableEvents = True
.
Note: I've removed your orginal Error Handlers, and I've added a way to deal with the VLookup
errors, by adding If IsError(suppname) Then
and If IsError(COMS) Then
.
Code
Private Sub Worksheet_Change(ByVal Target As Range)
Dim suppname As Variant
Dim COMS As Variant
Application.EnableEvents = False
If Not Intersect(Range("C3"), Target) Is Nothing Then
If Target.Value <> "" Then
suppname = Application.VLookup(Target.Value, Workbooks("Articlepassport.xlsm") _
.Sheets("SupplierNames").Range("B2:H1000"), 4, False)
If IsError(suppname) Then
Range("C5").Value = "Supplier Data not maintained!"
Else
Range("C5").Value = suppname
End If
Else
Range("C5") = ""
End If
End If
If Not Intersect(Range("C9"), Target) Is Nothing Then
If Target.Value <> "" Then
COMS = Application.VLookup(Target.Value, Workbooks("Articlepassport.xlsm") _
.Sheets("Tabelle2").Range("A2:B11000"), 2, False)
If IsError(COMS) Then
Range("C11").Value = "COMS does not exist!"
Else
Range("C11").Value = ""
End If
Else
Range("C11").Value = ""
End If
End If
Application.EnableEvents = True ' reset settings when leaving this Sub
End Sub