Excel VBA - Do Depending on Trigger

耗尽温柔 提交于 2019-12-25 01:29:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!