clayton33
clayton33

Reputation: 4216

If statement for VBA in Outlook

I am trying to make a template for doing our passdown in Outlook. I want it to say "Day Shift" in the subject line if it is between the hours of 0700 and 1900, and "Night Shift" otherwise. How can this be done.

What I have so far:

Sub MakeItem()
    Dim objMail As MailItem
    Set newItem = Application.CreateItemFromTemplate("C:\Passdown1.oft")
    newItem.Subject = "D1D NXE Day Shift Passdown " & Format(Now, "dd-mmm-yy")
    newItem.Display

    Set newItem = Nothing
End Sub

Upvotes: 0

Views: 4072

Answers (3)

Jeff
Jeff

Reputation: 918

Alternatively you could do this in one line:

newItem.Subject = String.Format("D1D NXE {0} Shift Passdown {1}", If(Date.Now.Hour >= 7 AndAlso Date.Now.Hour < 19, "Day", "Night"), Format(Now, "dd-MMM-yy"))

Upvotes: 1

PatricK
PatricK

Reputation: 6433

As my Comment, here is what you do...

Sub MakeItem()
    Dim objMail As MailItem
    Dim sShift As String ' Add this
    Set newItem = Application.CreateItemFromTemplate("C:\Passdown1.oft")
    ' Check hours
    Select Case Hour(Now)
        Case 7 To 18 ' Day shift until 18:59:59
            sShift = "Day"
        Case Else
            sShift = "Night"
    End Select
    ' Setup Subject replacing the <SHIFT>
    newItem.Subject = Replace("D1D NXE <SHIFT> Shift Passdown " & Format(Now, "dd-mmm-yy"), "<SHIFT>", sShift)
    newItem.Display

    Set newItem = Nothing
End Sub

Upvotes: 1

Kas
Kas

Reputation: 3923

Specify whatever condition for condition an specify a whatever statement to be excectued when condition is true

If condition [ Then ]
    [ statements ]
[ ElseIf elseifcondition [ Then ]
    [ elseifstatements ] ]
[ Else
    [ elsestatements ] ]
End If

' Single-line syntax:
If condition Then [ statements ] [ Else [ elsestatements ] ]

condition

Required. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to Boolean.

If the expression is a Nullable Boolean variable that evaluates to Nothing, the condition is treated as if the expression is not True, and the Else block is executed.

Then

Required in the single-line syntax; optional in the multiple-line syntax.

statements

Optional. One or more statements following If...Then that are executed if condition evaluates to True.

elseifcondition

Required if ElseIf is present. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to Boolean.

elseifstatements

Optional. One or more statements following ElseIf...Then that are executed if elseifcondition evaluates to True.

elsestatements

Optional. One or more statements that are executed if no previous condition or elseifcondition expression evaluates to True.

End If

Terminates the If...Then...Else block.

Upvotes: 0

Related Questions