[英]display email body of selected email in outlook as a message box in excel?
我正在使用excel 2010,並創建了以下vba代碼,該代碼查找在主題標題中包含單詞test的電子郵件,然后在excel中顯示帶有該電子郵件正文的消息框:
Sub GetFromInbox()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFldr As Outlook.MAPIFolder
Dim olItms As Outlook.Items
Dim olMail As Variant
Dim i As Long
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olItms = olFldr.Items
Set objItem = olApp.ActiveExplorer.Selection.Item(1)
olItms.Sort "Subject"
i = 1
For Each olMail In olItms
If InStr(olMail.Subject, "Test") > 0 Then
MsgBox olMail.Body
i = i + 1
End If
Next olMail
Set olFldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
我的最終目的是在代碼中添加條件(如果有條件的話),以便只有當前選擇的電子郵件或在Outlook中打開的電子郵件才能在我的excel消息框中顯示其電子郵件正文
例如,假設我們有幾封主題為“ test”的電子郵件,因為該代碼目前處於站立狀態,該代碼將在不同的消息框中依次顯示所有主題為“ test”的電子郵件的正文。
但是,如果Outlook中的當前選定/打開的電子郵件主題為“測試”,則應該只顯示一個消息框。
請有人能告訴我我該怎么做嗎?
您可以使用Application.ActiveInsepctor
屬性獲取打開的電子郵件,也可以使用Application.ActiveExplorer
屬性獲取選定但未打開的電子郵件
Sub GetFromInbox()
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Set olApp = New Outlook.Application
'If it's not an MailItem or there's no
'ActiveInspector, error is ignored
On Error Resume Next
Set olMail = olApp.ActiveInspector.CurrentItem
On Error GoTo 0
'If nothing is open, see if a MailItem is selected
If olMail Is Nothing Then
On Error Resume Next
Set olMail = olApp.ActiveExplorer.Selection.Item(1)
On Error GoTo 0
End If
If Not olMail Is Nothing Then
If InStr(olMail.Subject, "Test") > 0 Then
MsgBox olMail.Body
Else
MsgBox "Selected/active email does not have correct subject"
End If
Else
MsgBox "Active item is not an email or no email selected"
End If
End Sub
首先,它查找活動的,打開的項目。 如果這不是電子郵件,那么它將在“資源管理器”處於活動狀態的情況下查看第一個選定的項目。 如果那不是電子郵件,那么它將給您消息。
如果打開的活動項目是電子郵件,它將使用它並測試主題。 在這種情況下,它不會查看任何選定的項目。 僅當沒有未打開的內容或未打開的項目不是Mailitem(例如,它是CalendarItem)時,它才會查看所選內容。
例如,如果您在日歷中,則它是活動的瀏覽器,很可能任何選擇都不是MailItem。 它也不在乎您是否在另一個文件夾的收件箱中。 它只在乎選擇的第一個項目是MailItem。 您可以檢查olapp.ActiveExplorer.CurrentFolder
以確保您對收件箱很重要。
您可以在郵件文件夾中擁有不是MailItems的項目。 如果未選擇MailItem,則會收到一條消息。
最后,您可以在“收件箱”中選擇任意數量的項目。 這只會查看選擇的前幾項。 如果要處理所有項目,則可以使用.Selection.Count
和.Selection.Item(i)
瀏覽它們,依次處理每個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.