gohawks222
New Member
- Joined
- Feb 2, 2016
- Messages
- 21
This is the first time I have worked with Outlook within VBA, so go easy if I have any glaring mistakes. I get a report emailed every day in my standard inbox at 06:01, and I'm attempting to locate it based on that time criteria. There are no runtime errors, but when I step through and get to the end, oOltargetEmail contains no value. I've done a lot of research about the .Restrict() method formatting, and I think it's correct, but my guess is that's where the error is. Any ideas would be appreciated.
Code:
Const olFolderInbox As Integer = 6
Const AttachmentPath As String = "C:\Users\TRBYE\Desktop\cheeseReport.xlsx"
Private Sub CommandButton1_Click()
Dim oOlAp As Object, oOlns As Object, oOlInb As Object, oOlItm As Object, oOltargetEmail As Object, oOlAtch As Object
Dim beginningDate As String, endingDate As String, todaysDateTime As String, todaysDate As String, startTime As String, endTime As String
Dim x As Integer
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
startTime = " 06:00 AM"
endTime = " 06:02 AM"
todaysDateTime = Format(Now(), "ddddd hh:mm AMPM")
x = Len(todaysDateTime)
todaysDate = Left(todaysDateTime, (Len(todaysDateTime) - 9))
'set start and end time based on strings from above'
beginningDate = todaysDate & startTime
endingDate = todaysDate & endTime
'determine corrrect email'
For Each oOlItm In oOlInb.Items.Restrict("[Start] >= '" & beginningDate & "' and [End] <= '" & endingDate & "'")
If Left(oOlItm.Subject, 4) = "DGLD" Then
oOltargetEmail = oOlItm
Exit For
End If
Next
'download attachment to desktop'
For Each oOlAtch In oOltargetEmail.Attachments
oOlAtch.SaveAsFile AttachmentPath
Next
'open attachment'
Workbooks.Open (AttachmentPath)
End Sub