vbaoutlookms-word

If statement whether or not a sub has run


I am trying to run a if statement to send an email if the sub has run and is successful.

The current code I am trying is

Private Sub SendButton_Click()

Call Populate

If Populate = True Then
    Application.ScreenUpdating = False
    Set OL = CreateObject("Outlook.Application")
    Set EmailItem = OL.CreateItem(olMailItem)
    Set Doc = ActiveDocument
    Doc.Save

    With EmailItem
        .Subject = "New ePRF Available"
        .Body = "I have completed a new e-PRF"
        .To = ""
        .Importance = olImportanceNormal
        .attachments.Add Doc.FullName
        .Send
    End With

    Application.ScreenUpdating = True

    Set Doc = Nothing
    Set OL = Nothing
    Set EmailItem = Nothing
Else
    Call Populate
End If
End Sub

This is something I have never really done before so am very confused! Any help would be grateful!

Thanks


Solution

  • Make Populate a function and have it return a boolean value, then check that value in SendButton_Click

    I made a nonsense populate to show the general idea.

    Option Explicit
    
    Private Sub SendButton_Click()
    
    If populate() Then 'Test the return
        Application.ScreenUpdating = False
        Set OL = CreateObject("Outlook.Application")
        Set EmailItem = OL.CreateItem(olMailItem)
        Set Doc = ActiveDocument
        Doc.Save
    
        With EmailItem
            .Subject = "New ePRF Available"
            .Body = "I have completed a new e-PRF"
            .To = ""
            .Importance = olImportanceNormal
            .attachments.Add Doc.FullName
            .Send
        End With
    
        Application.ScreenUpdating = True
    
        Set Doc = Nothing
        Set OL = Nothing
        Set EmailItem = Nothing
    Else
        Call populate 'This is probably not what you actually want, but hard to tell without seeing populate
    End If
    End Sub
    
    Function populate() As Boolean 'specify the return type
        Dim returnval As Boolean
        Dim x As Boolean
        Dim y As Boolean
        
        returnval = True 'Start with true, if anything is false below flip the value
        
        x = True
        y = False
        'just showing the flow, you would be checking your userform values here
        If Not x Then
            returnval = False
        ElseIf Not y Then
            returnval = False
        End If
        
        populate = returnval 'return the value
    End Function