且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用VBA读取新的Outlook电子邮件?

更新时间:2023-11-30 08:21:52

您将需要以下内容:

Private WithEvents myOlItems  As Outlook.Items

Private Sub Application_Startup()
    Dim olApp As Outlook.Application
    Dim objNS As Outlook.NameSpace
      Set olApp = Outlook.Application
      Set objNS = olApp.GetNamespace("MAPI")
      Set myOlItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub myOlItems_ItemAdd(ByVal item As Object)

On Error GoTo ErrorHandler

  Dim Msg As Outlook.MailItem

  If TypeName(item) = "MailItem" Then
    Set Msg = item

    MsgBox Msg.Subject
    MsgBox Msg.Body

  End If

ProgramExit:
  Exit Sub
ErrorHandler:
  MsgBox Err.Number & " - " & Err.Description
  Resume ProgramExit
End Sub

将代码粘贴到ThisOutlookSession中,然后重新启动Outlook.当邮件进入默认的本地收件箱时,您会看到带有主题和正文的弹出窗口.

Paste the code into ThisOutlookSession and restart Outlook. When a message enters your default local Inbox you'll see the popup with subject and body.