Reputation: 708
There was one other question on here similar to this, and I implemented the advice there but I'm still unable to get this to return anything. Very simple; I get an email in my main inbox at 06:01 every day and that is what the oOltargetEmail should be set to at the end of this script. I believe the string in the .Restrict() is formatted correctly based on the documentation, but oOlItm never takes a value.
Const olFolderInbox As Integer = 6
Const AttachmentPath As String = "C:\Users\TRBYE\Desktop\cheeseReport.csv"
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, receivedTime As String, date1 As String
Dim x As Integer
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
receivedTime = " 06:01 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 & receivedTime
'determine corrrect email'
For Each oOlItm In oOlInb.Items.Restrict("[ReceivedTime] = '" & Format(beginningDate, "ddddd h:nn AMPM") & "'")
Set oOltargetEmail = oOlItm
Next
'download attachment to desktop'
For Each oOlAtch In oOltargetEmail.Attachments
oOlAtch.SaveAsFile AttachmentPath
Next
'open attachment'
Workbooks.Open (AttachmentPath)
End Sub
Upvotes: 0
Views: 253
Reputation: 708
Both of your advice helped in figuring this out. Here is what ending up working, just in case someone in the future stumbles upon this and can't figure it out. The main issue ended up being that the [ReceivedTime] never took a value because of the "=" operator like @Dmitry Streblechenko mentioned. Thanks for the help!
'determine corrrect email'
For Each oOlItm In oOlInb.Items.Restrict("[ReceivedTime] > '" & Format(beginningDate, "ddddd h:nn AMPM") & "' And [ReceivedTime] < '" & Format(endingDate, "ddddd h:nn AMPM") & "'")
Set oOltargetEmail = oOlItm
'download attachment to desktop'
For Each oOlAtch In oOltargetEmail.Attachments
oOlAtch.SaveAsFile AttachmentPath
Next
'open attachment'
Workbooks.Open(AttachmentPath)
Next
Upvotes: 0
Reputation: 66225
Never use "=" when working with the date/time properties - there will never be an exact match because of the round-off errors.
Upvotes: 1