【发布时间】:2017-08-27 11:00:52
【问题描述】:
请参考下面的代码。该代码将在 Excel VBA 中,然后运行它以便在 Outlook 中提取大量电子邮件。我有第二个问题,需要你的帮助。假设我的“收件箱”有大约 400 多封电子邮件。现在。下面的“For each next”代码开始查找最旧的电子邮件!那么,如果代码是从最新开始的,我该如何更改代码呢?
代码如下:
Sub GetFromInbox()
Dim olApp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMail As Variant
Dim i, ij As Integer
Dim tt As Date
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
i = 1
ij = 0
x = Date
' Now. the following "For each next " code starts to look in the oldest email!
' So how can I change the code if the code starts from the newest?
For Each olMail In Fldr.Items
ij = ij + 1
'If IsNumeric((Format(olMail.ReceivedTime, "dd/mm/yy"))) Then
Sheets("test").Range("a1").Select
Sheets("test").Range("I1").Clear
Sheets("test").Range("I2") = ij
Sheets("test").Range("I1").Value = (Format(olMail.ReceivedTime, "dd/mm/yy"))
Sheets("test").Range("I1").NumberFormat = "dd/mm/yy"
tt = Sheets("test").Range("I1")
' MsgBox ("Y-tt=" & tt & " receivedtime=" & olMail.ReceivedTime)
'Else
'tt = 0
'MsgBox ("N-tt=" & tt & " receivedtime=" & olMail.ReceivedTime)
'End If
' tt = CDate(Format(olMail.ReceivedTime, "dd/mm/yy"))
If tt >= Range("H1") Then
'If InStr(olMail.Subject, "others") > 0 And tt >= Range("h1") Then
If InStr(olMail.Subject, "others") > 0 Then
ActiveSheet.Range("h2") = "y"
ActiveSheet.Cells(i, 1).Value = olMail.Subject
ActiveSheet.Cells(i, 2).Value = olMail.ReceivedTime
ActiveSheet.Cells(i, 3).Value = olMail.SenderName
tt = CDate(Format(olMail.ReceivedTime, "dd/mm/yy"))
ActiveSheet.Cells(i, 4).Value = CDate(Format(olMail.ReceivedTime, "dd/mm/yy"))
' tt = ActiveSheet.Cells(i, 4).Value
ActiveSheet.Cells(i, 5).Value = (Format(olMail.ReceivedTime, "hh:mm"))
MsgBox ("tt=" & tt)
i = i + 1
End If
Else
Sheets("test").Range("h2") = "N"
End If
Next olMail
Set Fldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
'tt = ""
End Sub
【问题讨论】:
-
试试
For i = Fldr.Items.Count to 1 Step -1怎么样? -
olmail 呢? olmail 是 For Each Next 代码中的主要功能!!!上面的代码——我通过互联网搜索它,然后为我的案例更改/更新!!!据我了解,olmail 指的是“收件箱”中的每封邮件!所以你的想法可能行不通,但我不确定!如果我错了请告诉我
-
在这种情况下,您可以将
olMail替换为Fldr.Items(i)。由于您已经在使用i,您可以将其替换为另一个变量名(如“j”)。 -
^^ 并且,为了对代码进行最少的更改,只需在
For j = Fldr.Items.Count To 1 Step -1行之后立即使用Set olMail = Fldr.Items(j)。这会将更改的数量限制为仅 4 行 - (1) j 的声明 (2)For行 (3) 新的Set olMail行 (4)Next行。 -
谢谢以上所有!!有用 !!太棒了!!