首先,我是一名VB新手,从头开始工作,但过去曾编辑过一些代码。我能找到的最接近的问题是this one,但没有我希望的那么具体。
因此,我使用的是Outlook / Excel 2007,并且每天都会收到一封电子邮件,其中包含一些固定格式的数据。我希望做的是设置一个宏/脚本,该宏/脚本将搜索我的Outlook收件箱,然后基于正确的邮件主题,将在邮件正文中查找并将某些部分提取到Excel工作表中。
根据我的知识,我认为VB可能是最好的方法,但是我不确定从哪里开始。对于代码或其他类似示例的一般结构的任何帮助,将不胜感激。只是想入门,并希望自己自己解决这个问题,以备将来练习。谢谢!
因此,非常感谢您的帮助!我大部分已经完成了这项工作,但是当我收到新消息时,我只是无法使其自动更新。我有一个规则设置,可以将相关电子邮件移动到它们自己的文件夹中,并且能够设置一个可以运行的公共宏,该宏可以提取所有数据(针对每封电子邮件)并将其转储为.csv文件。
我试图将该宏改编为您上面发布的示例,当我收到新消息时该宏应自动运行,但我尚未成功。电子邮件的解析不应更改(并且肯定可以在手动运行的宏中使用),所以很好,它只是使自动更新宏可以在新邮件上运行。我想念什么吗?这是我所得到的,除了新文件夹(它是一个类模块)外,与上面的示例基本相同:
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)是解决特定问题的最简单且可互操作性最高的语言。
您首先要创建一个新的Outlook宏,当新邮件到达收件箱时该宏就会触发。
首先在Outlook(ALT-F11)中创建一个新的类模块,然后复制以下代码:
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并执行您想做的任何事情。确保通过使用“工具:参考...”菜单项并选择Microsoft Excel xx.xx对象库来建立对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方法的实际数据处理部分。
希望这足以让您入门。
关于excel - 使用VB/VBA搜索Outlook邮件并将特定数据提取到Excel工作表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5826158/