I am a beginner with VBA. I am not setting the MailItem correctly. The command to get the Body of the email is not pulling the body from the active email. Not sure how to set the itm correctly for the "sText = itm.Body" command.
Dim itm As Outlook.MailItem
Dim currentExplorer As Explorer
Dim Selection As Selection
Dim strFileName As String, strExt As String
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim email_date As Date
Dim date_ext As String
Dim sText As String
Dim Intext_date As String
Dim Mail_date As Date
Dim email_date_temp As String
saveFolder = "C:\elan\Various\email_attachments\"
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
For Each itm In Selection
For Each objAtt In itm.Attachments
strFileName = objAtt.DisplayName
' get the last 5 characters or last 4 for .xls for the file extension
strExt = Right(objAtt.DisplayName, 5)
If Mid(strExt, 1, 1) <> "." Then
strExt = Right(objAtt.DisplayName, 4)
End If
If strExt = ".xls" Or strExt = ".xlsx" Then
' clean the File Name
ReplaceCharsForFileName strFileName, "-"
' Get Body of email
Set itm = ActiveExplorer.Selection.item(1)
sText = itm.Body
Debug.Print sText
CodePudding user response:
There is no need to set the itm
object in the code in the following way:
Set itm = ActiveExplorer.Selection.item(1)
In your code the itm
object is already assigned with each loop iteration:
For Each itm In Selection
So, the code could look like that:
For Each itm In Selection
For Each objAtt In itm.Attachments
strFileName = objAtt.DisplayName
' get the last 5 characters or last 4 for .xls for the file extension
strExt = Right(objAtt.DisplayName, 5)
If Mid(strExt, 1, 1) <> "." Then
strExt = Right(objAtt.DisplayName, 4)
End If
If strExt = ".xls" Or strExt = ".xlsx" Then
' clean the File Name
ReplaceCharsForFileName strFileName, "-"
' Get Body of email
sText = itm.Body
Debug.Print sText
Remember that you get the message body in the inner loop which means if you have multiple attached files you will get the same message body for each of them.