How to run a VBA macro when new mail is received in Outlook

It can be very useful to run a VBA macro when new mail is received in Outlook. A customer asked me to write something that would log an entry to a SQL database when an email produced contact form was received.

It’s easy to do but can take a bit of trial and error to get working just how you want it.

You need to add an event listener to the Inbox which will process incoming messages. A the following code to ThisOutlookSession:

  1. Option Explicit
  2. Private WithEvents inboxItems As Outlook.Items
  3. Private Sub Application_Startup()
  4. Dim outlookApp As Outlook.Application
  5. Dim objectNS As Outlook.NameSpace
  6. Set outlookApp = Outlook.Application
  7. Set objectNS = outlookApp.GetNamespace("MAPI")
  8. Set inboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
  9. End Sub
  10. Private Sub inboxItems_ItemAdd(ByVal Item As Object)
  11. On Error GoTo ErrorHandler
  12. Dim Msg As Outlook.MailItem
  13. Dim MessageInfo
  14. Dim Result
  15. If TypeName(Item) = "MailItem" Then
  16. MessageInfo = "" & _
  17. "Sender : " & Item.SenderEmailAddress & vbCrLf & _
  18. "Sent : " & Item.SentOn & vbCrLf & _
  19. "Received : " & Item.ReceivedTime & vbCrLf & _
  20. "Subject : " & Item.Subject & vbCrLf & _
  21. "Size : " & Item.Size & vbCrLf & _
  22. "Message Body : " & vbCrLf & Item.Body
  23. Result = MsgBox(MessageInfo, vbOKOnly, "New Message Received")
  24. End If
  25. ExitNewItem:
  26. Exit Sub
  27. ErrorHandler:
  28. MsgBox Err.Number & " - " & Err.Description
  29. Resume ExitNewItem
  30. End Sub

Screenshot showing the location of where to paste code into ThisOutlookSession to trigger a macro when new mail is received.

You need to restart Outlook for the code to become active.

The above code will produce a simple message box that shows some of the message properties:

Screenshot of VBA Macro being triggered when new mail is received in Outlook

You can of course do whatever you like with the message when it is received. I used it to insert rows into a SQL table, then move the message to a different folder. It works very well.

It’s worth taking a look at all of the available properties of the Outlook mailitem that are available.

If you found this post helpful, I’d really appreciate it if you would rate it ?

Let me know in the comments section if you have any questions.

转载于:https://www.cnblogs.com/jjj250/p/11598144.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值