限制具有多个日期条件的方法筛选器



我正在尝试使用Excel VBA过滤掉我的Outlook邮件收件箱,然后在条件满足的情况下最终发送电子邮件。

完整条件为:如果Outlook收件箱包含日期范围(过去7天)和发件人(动态发件人电子邮件)的主题。

我已经完成了sub sendEmails(),现在正在努力过滤邮件。

我现在已成功过滤掉我正在查看的主题的代码。 但是,在尝试将日期范围包含在筛选器中后, 它搞砸了。

第一个问题:过滤器给了我

运行时错误 13:类型不匹配。

我知道会发生这种情况,因为过滤器包含StringDate值,所以我尝试将类型更改为variant但仍然遇到错误。

另一个问题是我关注这篇文章以尝试添加日期条件。和这篇文章应用日期过滤器。 如果有经验的人可以纠正我的错误,请正确处理许多错误。 (还没跑到那里,但只是有强烈的感觉就会打错)

这是我第一次使用这个,所以请放轻松。

Sub Search_Inbox()
Dim myOlApp As New Outlook.Application
Dim objNamespace As Outlook.Namespace
Dim objFolder As Outlook.MAPIFolder
Dim filteredItems As Outlook.Items
Dim itm As Object
Dim Found As Boolean
Dim Filter As Variant
Dim tdyDate As String
Dim checkDate As Date
tdyDate = Format(Now(), "Short Date")
checkDate = DateAdd("d", -7, tdyDate) ' DateAdd(interval,number,date)
Set objNamespace = myOlApp.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)
'https://msdn.microsoft.com/en-us/library/aa579702(v=exchg.80).aspx
Filter = "@SQL=" & Chr(34) & "(urn:schemas:httpmail:subject" & Chr(34) & " like 'Reminder on Subject' &" _
And Chr(34) & "urn:schemas:httpmail:datereceived >= & checkDate &  " _
And Chr(34) & "urn:schemas:httpmail:datereceived >= & tdyDate &"
Set filteredItems = objFolder.Items.Restrict(Filter)
If filteredItems.Count = 0 Then
Debug.Print "No emails found"
Found = False
Else
Found = True
' this loop is optional, it displays the list of emails by subject.
For Each itm In filteredItems
Debug.Print itm.Subject
Next
End If

'If the subject isn't found:
If Not Found Then
'NoResults.Show
Else
Debug.Print "Found " & filteredItems.Count & " items."
End If
Set myOlApp = Nothing
End Sub

假设您只是在添加日期文件管理器时遇到问题,您可以在此处找到有用的内容。
现在将其应用于您的代码,您必须用单引号 (') 将日期括起来。

尽管日期和时间通常以 Date 格式存储,但 Find 和 Limit 方法要求将日期和时间转换为字符串表示形式。

Dim tdyDate As String, checkDate As String
tdyDate = "'" & Format(Date, "Short Date") & "'"
checkDate = "'" & Format(Date - 7, "Short Date") & "'"

或者,您可以尝试:

tdyDate = Format(Date, "'ddddd'") '/* until todays date */
checkDate = Format(Date - 7, "'ddddd'") '/* I suppose you are filtering 7 days ago? */

然后构造过滤器:

eFilter = "@SQL= (urn:schemas:httpmail:subject Like 'Reminder on Subject'" & _
" And urn:schemas:httpmail:datereceived >= " & checkDate & _
" And urn:schemas:httpmail:datereceived <= " & tdyDate & ")"

备注:我使用eFilter而不是Filter作为变量,因为它是VBA中的保留字。

这将为您提供:

@SQL= (urn:schemas:httpmail:subject Like 'Reminder on Subject' 和 urn:schemas:httpmail:datereceived>= '1/2/2018'

和 urn:schemas:httpmail:datereceived <= '1/9/2018')

最新更新