使用VB / VBAsearchOutlook邮件并将特定数据提取到Excel工作表中

首先,我是一个VB新手,从头开始工作,但过去编辑过一些代码。 我能find的最接近的问题是这个问题,但并不像我希望的那么具体。

所以我使用Outlook / Excel 2007,每天收到一封包含固定格式数据的电子邮件。 我希望做的是build立一个macros/脚本,将search我的Outlook收件箱,然后基于正确的邮件主题,将查看邮件的正文,并提取到Excel工作表中的某些部分。

我认为VB可能是根据我的知识做到这一点的最好方法,但我不太确定从哪里开始。 任何帮助的代码或其他类似的例子的一般结构将不胜感激。 只是想开始,希望能够自己解决未来的练习。 谢谢!


所以非常感谢您的帮助! 我主要得到这个工作,当我得到一个新的消息,我只是无法让它自动更新。 我有一个规则设置,将相关的电子邮件移动到他们自己的文件夹,我能够build立一个公共的macros,我可以运行,拉出所有的数据(每个电子邮件),并将其转储到.csv文件。

我试图将这个macros调整到上面发布的例子中,当我收到一条新消息时它会自动运行,但是我还没有成功。 电子邮件的parsing不应该改变(并且肯定在手动运行的macros中有效),所以这很好,只是让自动更新macros运行在一个新的消息上。 我错过了什么吗? 这是我得到的,这是基本上与上面的例子除了新的文件夹(是一个类模块)相同:

Public WithEvents myOlItems As Outlook.Items Public Sub Application_Startup() ' Reference the items in the Inbox. Because myOlItems is declared ' "WithEvents" the ItemAdd event will fire below. Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Folders("FolderX").Items End Sub Private Sub myOlItems_ItemAdd(ByVal Item As Object) Dim objOutlook As New Outlook.Application Dim objNameSpace As Outlook.NameSpace Dim objFolder As Outlook.MAPIFolder Dim objMail As MailItem Dim count As Integer Dim myTitlePos As Integer Dim myTitleLen As Integer Dim myVarPos As Integer Dim myVarLen As Integer Dim strPrice As String Dim strYear As String Dim myVarCRLF As Integer Dim myDate As Date Dim newLineTest As String ' Check to make sure it is an Outlook mail message, otherwise ' subsequent code will probably fail depending on what type ' of item it is. If TypeName(Item) = "MailItem" Then ' Data processing and parsing is done here End Sub 

VB可能是最简单的语言来处理您的问题,因为您是所有这些新手,VBA(Visual Basic for Applications)是针对特定问题的最简单,最具互操作性的语言。

您将首先创build一个新的Outlookmacros,当新邮件到达您的收件箱时触发。

首先在Outlook(ALT-F11)中创build一个新的类模块并复制以下代码:

 Public WithEvents myOlItems As Outlook.Items Public Sub Application_Startup() ' Reference the items in the Inbox. Because myOlItems is declared ' "WithEvents" the ItemAdd event will fire below. Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Items End Sub Private Sub myOlItems_ItemAdd(ByVal Item As Object) ' Check to make sure it is an Outlook mail message, otherwise ' subsequent code will probably fail depending on what type ' of item it is. If TypeName(Item) = "MailItem" Then If Item.Subject = "My Required Subject Line" Then ' Here's where you want to do some stuff. End If End If End Sub 

接下来的部分是打开Excel,做任何你想做的事情。 确保通过使用“工具:参考…”菜单项并selectMicrosoft Excel xx.xx对象库来build立对excel对象库的引用。

你可能会需要像下面这样的代码:

 Private Sub Do_Excel_Stuff(MyContent As Object) Dim myXLApp As Excel.Application Dim myXLWB As Excel.Workbook Set myXLApp = New Excel.Application Set myXLWB = New Excel.Workbook ' Do your data processing here Set myXLWB = Nothing Set myXLApp = Nothing End Sub 

这可能会从您的myOlItems_ItemAdd方法中调用。

有些在Google或Stack Overflow上浏览应该会给你足够的关于如何处理Excel方法的实际数据处理部分的指针。

希望这足以让你开始。