2012-06-28 29 views
1

我正在使用VBA檢查單元格的值,並調用電子郵件模塊發送電子郵件,如果單元格的值超過一個值。合併兩個私人小組Worksheet_Change

我想檢查多個單元,但明白在VBA中不能有兩個Private Sub Worksheet_Change。檢查多個單元格的最佳方法是什麼?

這是我使用的代碼;

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 

這裏是另一個可能的話,我想合併到一個子

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 
+0

爲什麼不把'If Not Application.Intersect ...'塊同時放到同一個Sub中? –

回答

0

這樣做怎麼樣?

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 
+0

謝謝!我得到一個語法錯誤,需要在Mailalert之前添加一個Call,但它現在正在工作。 –

0
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 

可能有更有效的方式,但是這是第一個浮現在腦海。希望這回答你的問題。