我正在寻找一种明确的方法,可以在收到电子邮件时使用vba来阅读主题行,以便创建新文件夹或只使用现有文件夹将电子邮件移入。我看过一些vba示例,但没有一个解决vba编辑器中带有outlook的新邮件方法。
答案 0 :(得分:1)
查看this article,特别是方法2和3,我想这会指出你正确的方向。
答案 1 :(得分:0)
我只是为此编写了代码。我的宏搜索电子邮件以查找特定字符串,然后在此之后获取所有内容并使用该名称创建文件夹。你需要一些功能来: 1)检查文件夹是否已存在 2)如果没有,则创建它 3)将MailItem移动到新文件夹 4)调用这些函数
注意:其中大部分是硬编码的,如果需要,可以更改为接受用户输入。此外,它不适用于子文件夹(您必须自定义)。
1)检查文件夹:
Function CheckForFolder(strFolder As String) As Boolean
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim olInbox As Outlook.MAPIFolder
Dim FolderToCheck As Outlook.MAPIFolder
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set olInbox = olNS.GetDefaultFolder(olFolderInbox)
On Error Resume Next
Set FolderToCheck = olInbox.Folders(strFolder)
On Error GoTo 0
If Not FolderToCheck Is Nothing Then
CheckForFolder = True
End If
ExitProc:
Set FolderToCheck = Nothing
Set olInbox = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Function
2)创建:
Function CreateSubFolder(strFolder As String) As Outlook.MAPIFolder
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim olInbox As Outlook.MAPIFolder
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set olInbox = olNS.GetDefaultFolder(olFolderInbox)
Set CreateSubFolder = olInbox.Folders.Add(strFolder)
ExitProc:
Set olInbox = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Function
3)搜索并移动:
Function SearchAndMove(lookFor As String)
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim olInbox As Outlook.MAPIFolder
Dim FolderToCheck As Outlook.MAPIFolder
Dim myItem As Object
Dim MyFolder As Outlook.MAPIFolder
Dim lookIn As String
Dim newName As String
Dim location As Integer
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set olInbox = olNS.GetDefaultFolder(olFolderInbox)
For Each myItem In olInbox.Items
lookIn = myItem.Subject
If InStr(lookIn, lookFor) Then
location = InStr(lookIn, lookFor)
newName = Mid(lookIn, location)
If CheckForFolder(newName) = False Then
Set MyFolder = CreateSubFolder(newName)
myItem.Move MyFolder
Else
Set MyFolder = olInbox.Folders(newName)
myItem.Move MyFolder
End If
End If
Next myItem
End Function
4)通话功能:
Sub myMacro()
Dim str as String
str = "Thing to look for in the subjectline"
SearchAndMove (str)
End Sub