简体   繁体   中英

Combine two Private Sub Worksheet_Change

I am using VBA to check a value of a cell and call an email module to email if the cell's value is more than a value.

I want to check multiple cells but understand that it is not possible to have two Private Sub Worksheet_Change in VBA. What is the best way to check multiple cells?

Here is the code I am using;

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("A1"), Target) Is Nothing Then
        If IsNumeric(Target.Value) And Target.Value > 10 Then
        Call Mail_small_Text_Outlook
        End If
    End If
End Sub

Here is another if possible I would like to combine into the one Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("B1"), Target) Is Nothing Then
        If IsNumeric(Target.Value) And Target.Value > 20 Then
        Call Mail_small_Text_Outlook
        End If
    End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)

Select Case Taget.Address

  Case "$A$1" 'This will make sure its just one cell and its A1          
      If IsNumeric(Target.Value) And Target.Value > 10 Then         
        Call Mail_small_Text_Outlook         
      End If     

  Case "$B$1" 'This will make sure its just one cell and its B1
      If IsNumeric(Target.Value) And Target.Value > 20 Then         
        Call Mail_small_Text_Outlook         
      End If 

  'Case ... whatever else you want.

End Select
End Sub

There may be more efficient ways, but this is what first came to mind. Hope this answers your question.

How about doing this?

Private Sub Worksheet_Change(ByVal Target As Range)
    Call MailAlert(Target, "A1", 10)
    Call MailAlert(Target, "B1", 20)
End Sub

Private Sub MailAlert(ByVal Target As Range, ByVal Address As String, ByVal Value As Integer)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range(Address), Target) Is Nothing Then
        If IsNumeric(Target.Value) And Target.Value > Value Then
        Call Mail_small_Text_Outlook
        End If
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM