このサイトは、受信メールの処理の自動化に非常に役立ちます。ここで Outlook VBA を動作させるためのヒントを読むことを強くお勧めします。
このコードは、そのページからわずかに変更されています。TODO で始まるコメント行はまだ入力する必要がありますが、これで正しい軌道に乗ることができます。
Option Explicit
'
' Place this code in the "ThisOutlookSession" class module
'
' The code will:
'
' Monitor the Inbox
' Check for the existence of a specific kind of e-mail
' Move the processed e-mail to a "processed" folder
'
Private WithEvents olInboxItems As Items
'
' Application_Startup() is a reserved function that will automatically
' be called when Outlook starts.
'
Private Sub Application_Startup()
Set olInboxItems = Session.GetDefaultFolder(olFolderInbox).Items
End Sub
'
' This event is fired when the Inbox receives a new message
' (it can also be fired when manually moving a message from
' another folder back to the inbox)
'
Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
' On Error Resume Next (commented out for ease of debugging)
Dim olMailItem As MailItem
Dim strAttachmentName As String
Dim Employee() As Variant
Dim v() As String
Dim i As Long
Dim NumItems As Long
Dim line As Variant
'
' Only inspect mail items
' Ignore appointments, meetings, tasks, etc.
'
If TypeOf Item Is MailItem Then
Set olMailItem = Item
'
' Test for specific subject line
'
If InStr(olMailItem.Subject, "My Subject Line") > 0 Then
' Get an array of lines in the body of the email
v = Split(olMailItem.Body, vbCrLf)
' TODO Parse the array for the data required to populate your Excel file
' TODO Open (or activate) the Excel file
' TODO Add the data to the Excel file
' Once complete, move mail item to OK/Errors folder
' This code assumes the folders already exist
' and are subfolders of the Inbox folder
'
' In older versions of Outlook, olDestFolder
' should be declared as type MAPIFolder
' instead of Folder
'
Dim olDestFolder As Folder, strFolderName As String
If Err.Number Then
strFolderName = "Processed_Errors"
Else
strFolderName = "Processed_OK"
End If
'
' Display Message
'
Set olDestFolder = _
Session.GetDefaultFolder(olFolderInbox).Folders(strFolderName)
If Err.Number Then
olMailItem.Move olDestFolder
MsgBox Err.Description + strFolderName + vbCrLf + _
"Check the error folder", _
vbCritical, "Automated e-Mail processing unsuccessful"
Else
olMailItem.Move olDestFolder
MsgBox "Message has been processed and placed in " + strFolderName, _
vbInformation, "Automated e-Mail processing successful"
End If
End If
End If
Set Item = Nothing
Set olMailItem = Nothing
End Sub