问题
I am trying to change the mail body depending on the macro which trigger the macro called "SendFromGmail"
Sub SendFromGmail()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Set NewMail = New CDO.Message
Set rng1 = Worksheets("Sheet3").Range("H22")
Set rng2 = Worksheets("Sheet4").Range("H14")
Set rng3 = Worksheets("Sheet5").Range("H18")
'bla bla bla
'...
'...
If rng1.Value > 0.02 Then
HTMLBody = "XYZ is up more than" & RangetoHTML(rng1)
ElseIf rng2.Value > 0.02 Then
.HTMLBody = "XYZ is up more than" & RangetoHTML(rng2)
ElseIf rng3.Value > 0.02 Then
.HTMLBody = "XYZ is up more than" & RangetoHTML(rng3)
End If
But if rgn1
is above 0.02 and then rgn2
is changed and rise above 0.02 the mail is only sent for rgn1
.
I want to change the subject according to macro the request came from
'This is on Sheet3
Private Sub Worksheet_Calculate()
Application.ScreenUpdating = False
If Range("H22").Value > 0.02 Then
Call SendFromGmail
End If
Application.ScreenUpdating = True
End Sub
'This is on sheet4
Private Sub Worksheet_Calculate()
Application.ScreenUpdating = False
If Range("H14").Value > 0.02 Then
Call Gmail
End If
Application.ScreenUpdating = True
End Sub
回答1:
You make worksheet calculate events pass the relevant range:
'This is on sheet3
Private Sub Worksheet_Calculate()
If Range("H22").Value > 0.02 Then SendFromGmail Range("H22") ‘ pass the relevant range reference to SendFromGmail()
End Sub
'This is on sheet4
Private Sub Worksheet_Calculate()
If Range("H14").Value > 0.02 Then Gmail Range("H14")
End Sub
And change SendFromGmail() sub to accept a Range parameter
Sub SendFromGmail(rng As Range) ‘the sub wants a Range parameter
Application.ScreenUpdating = False
Set NewMail = New CDO.Message
'bla bla bla
'...
'...
If rng.Value > 0.02 Then
.HTMLBody = "XYZ is up more than" & RangetoHTML(rng)
End If
Application.ScreenUpdating = True
You can also change the body in relation to rng sheet:
Select Case rng.Parent.Name
Case "Sheet3"
.HTMLBody = ... ‘your text to account for coming from Sheet3
Case "Sheet2"
.HTMLBody = ... ‘your text to account for coming from Sheet2
End Select
来源:https://stackoverflow.com/questions/48973260/excel-vba-do-depending-on-trigger