We use Outlook 2010 and receive emails with Excel attachments. We manually save the attachment in a sub-folder that we create within a divisional folder on a network drive.
What I'm curious about is if it's possible to
Use code to check incoming emails to see if they have an attachment,
Then check the attachment to see if it's an .XLSX,
If so, open the attachment, check the value of a particular cell,
then store the account name and account number as a string and a variable
then use those to create the sub-folders in the appropriate Windows directory.
** I forgot to post what I had done so far. I believe Brett answered my ??, but maybe someone else would be able to use snippets of it.
Private Sub cmdConnectToOutlook_Click()
Dim appOutlook As Outlook.Application
Dim ns As Outlook.Namespace
Dim inbox As Outlook.MAPIFolder
Dim item As Object
Dim atmt As Outlook.Attachment
Dim filename As String
Dim i As Integer
Set appOutlook = GetObject(, "Outlook.Application")
Set ns = appOutlook.GetNamespace("MAPI")
Set inbox = ns.GetDefaultFolder(olFolderInbox)
i = 0
If inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, _
"Nothing Found"
Exit Sub
End If
For Each item In inbox.Items
For Each atmt In item.Attachments
If Right(atmt.filename, 4) = "xlsx" Then
filename = "\\temp\" & atmt.filename
atmt.SaveAsFile filename
i = i + 1
End If
Next atmt
Next item
MsgBox "Attachments have been saved.", vbInformation, "Finished"
Set atmt = Nothing
Set item = Nothing
Set ns = Nothing
End Sub
Having said it is lengthy here is one way to do it. My code from VBA Code to save an attachment (excel file) from an Outlook email that was inside another email as an attachment may also be of interest
You will need to update your file path, and the cell range from the file that you are opening
In my testing I sent a message to myself with a pdf file and an excel workbook with "bob" in the A1 in the first sheet
The code below found the excel file, saved it, opened it, create a directory c:\temp\bob then killed the saved file
Private Sub Application_NewMailEx _
(ByVal EntryIDCollection As String)
'Uses the new mail techniquer from http://www.outlookcode.com/article.aspx?id=62
Dim arr() As String
Dim lngCnt As Long
Dim olAtt As Attachment
Dim strFolder As String
Dim strFileName As String
Dim strNewFolder
Dim olns As Outlook.NameSpace
Dim olItem As MailItem
Dim objExcel As Object
Dim objWB As Object
'Open Excel in the background
Set objExcel = CreateObject("excel.application")
'Set working folder
strFolder = "c:\temp"
On Error Resume Next
Set olns = Application.Session
arr = Split(EntryIDCollection, ",")
On Error GoTo 0
For lngCnt = 0 To UBound(arr)
Set olItem = olns.GetItemFromID(arr(lngCnt))
'Check new item is a mail message
If olItem.Class = olMail Then
'Force code to count attachments
DoEvents
For Each olAtt In olItem.Attachments
'Check attachments have at least 5 characters before matching a ".xlsx" string
If Len(olAtt.FileName) >= 5 Then
If Right$(olAtt.FileName, 5) = ".xlsx" Then
strFileName = strFolder & "\" & olAtt.FileName
'Save xl attachemnt to working folder
olAtt.SaveAsFile strFileName
On Error Resume Next
'Open excel workbook and make a sub directory in the working folder with the value from A1 of the first sheet
Set objWB = objExcel.Workbooks.Open(strFileName)
MkDir strFolder & "\" & objWB.sheets(1).Range("A1")
'Close the xl file
objWB.Close False
'Delete the saved attachment
Kill strFileName
On Error Goto 0
End If
End If
Next
End If
Next
'tidy up
Set olns = Nothing
Set olItem = Nothing
objExcel.Quit
Set objExcel = Nothing
End Sub
Related
What I'm trying to do is make a loop to send an email to a list of people, with each person receiving their own excel file. The first part hasn't been set up, so I have placeholder information for who it's going to, but I'm having problems with attachments. The program works fine without the attachments line, but when I add that, I get the aforementioned error, and I'm stumped on how to fix it.
Sub AttachAndEmail()
Dim fileDirectory As String
Dim fileCriteria As String
Dim fileName As String
Dim emailApplication As Object
Dim emailItem As Object
On Error Resume Next
Set emailApplication = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set emailApplication = CreateObject("Outlook.Application")
Set emailItem = emailApplication.CreateItem(0)
On Error GoTo 0
Application.ScreenUpdating = False
fileDirectory = "C:\Users\DW1085\Downloads\a\"
fileName = Dir(fileDirectory)
Do While Len(fileName) > 0
emailItem.to = "Myname#email.com"
emailItem.Subject = "WowweWow"
emailItem.Body = "Yup"
emailItem.Attachments.Add fileName
emailItem.Display
fileName = Dir
Loop
Application.ScreenUpdating = True
End Sub
The Attachments.Add method creates a new attachment in the Attachments collection. The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment. So, you need to pass a full path to the file you want to be attached. For example:
Sub AddAttachment()
Dim myItem As Outlook.MailItem
Dim myAttachments As Outlook.Attachments
Set myItem = Application.CreateItem(olMailItem)
Set myAttachments = myItem.Attachments
myAttachments.Add "C:\Test.doc", olByValue, 1, "Test"
myItem.Display
End Sub
I have a code that will:
Go to a specific folder ("Company A status report") which is below the shared mailbox (Inquiry#company.com).
Search for unread emails + a subject phrase: "Company A status report"
Take emails that match the criteria, find the last email then check if an attachment exists.
If attachments exist then download the file.
The code has previously worked, but now I get an error at this line:
Set olFolder = oOlns.GetSharedDefaultFolder(olShareName, olFolderInbox) '// Inbox
The error is:
"assignment to constant not permitted"
Library references
Option Explicit
Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\Projects\Attachments"
Sub DownloadAttachmentFirstUnreadEmail()
Dim oOlInbFiltered As Variant
Dim oOlAp As Object, oOlns As Object, oOlInb As Object
Dim oOlItm As Object, oOlItmF As Object, oOlAtch As Object
'~~> New File Name for the attachment
Dim NewFileName As String
NewFileName = AttachmentPath & Format(Date, "DD-MM-YYYY") & " - "
'~~> Get Outlook instance
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
'Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox).Folders("Company A status report") 'If outlook only contain the following:
'Looks in Inbox
'-Personal Inbox
'-Company A status report
Dim olShareName As Object
'https://superuser.com/questions/1035062/how-to-run-a-macro-on-a-shared-mailbox-in-outlook-2013
Set olShareName = oOlns.CreateRecipient("Inquiry#company.com") '// Owner's email address
Set olFolder = oOlns.GetSharedDefaultFolder(olShareName, olFolderInbox) '// Inbox
Set oOlInb = olFolder.Folders("Company A status report")
'Looks in Shared Inbox
'-Personal Inbox
'-Inquiry Inbox (Shared)
'-Company A status report
'~~> Check if there are any actual unread emails
If oOlInb.Items.Restrict("[UnRead] = True").Count = 0 Then
MsgBox "NO Unread Email In Inbox"
Exit Sub
End If
'https://stackoverflow.com/questions/30464271/find-an-email-starting-with-specific-subject-using-vba
'~~> Filter all unread mails with the subject: Company A status report
Dim Findvariable As String
Findvariable = "Company A status report"
Dim filterStr As String
filterStr = "#SQL=" & "urn:schemas:httpmail:subject like '%" & Findvariable & "%'"
Set oOlInbFiltered = oOlInb.Items.Restrict(filterStr)
Set oOlInbFiltered = oOlInb.Items.Restrict("[UnRead] = True")
'Set oOlInbFiltered = oOlInb.Items.Restrict("[UnRead] = True AND [Subject] = 'Company A status report'") - works
'Test how many mails that are found and populated in the variable: oOlInbFiltered
MsgBox ("Hello Test")
Dim testp As Object
For Each testp In oOlInbFiltered
Debug.Print testp.Subject
Next testp
'Sort all the mails by ReceivedTime so the loop will start with the latest mail
oOlInbFiltered.Sort "ReceivedTime", True 'True for Ascending. Take the last mail to the oldest. We only want the last and therefore exit the loop after we find it.
For Each oOlItm In oOlInbFiltered
'Debug.Print oOlItm
'~~> Check if the email actually has an attachment
If oOlItm.Attachments.Count <> 0 Then
For Each oOlAtch In oOlItm.Attachments
Debug.Print oOlAtch
'~~> Download the attachment
oOlAtch.SaveAsFile NewFileName & oOlAtch.FileName
'Mark the found mail as read
oOlItm.UnRead = False
DoEvents
oOlItm.Save
Exit For
Next
Else
MsgBox "The Email doesn't have an attachment"
End If
Exit For
Next oOlItm
'Open the downloaded file
Dim wb As Workbook
Dim FilePath As String
FilePath = NewFileName & oOlAtch.FileName
Set wb = Workbooks.Open(FilePath)
'Set DataPage = wb1.Sheets("DATA")
End Sub
Sorry but can't comment yet.
Error might be caused by:
Const olFolderInbox As Integer = 6
If you change it to normal olFolderInbox = 6 it might fix your issue.
I've got similar vba, that opens inbox and then check's e-mail details and iterate through them.
On mine I've set different Dim's
Dim myOlApp As New Outlook.Application
Dim filteredItems As Outlook.Items
Dim Ns As Outlook.Namespace
Dim Folder As Outlook.Folder
Dim olSharedName As Outlook.Recipient
Where
Set Ns = myOlApp.GetNamespace("MAPI")
Set olSharedName = Ns.CreateRecipient("e'mail#domain.com")
Set Folder = Ns.GetSharedDefaultFolder(olSharedName, olFolderInbox)
My references are:
Hope I've helped.
I've the below code that I'm using in outlook to download an attachment from a list of emails.
The code works fine for the first iteration of the loop, but on the second iteration it errors with Run-time error '91' Object variable or With block variable not set at the step where it is attempting to save the file to a temporary folder on the desktop (i.e. the line wb.SaveAs FileFormat:=51, FileName:=xlNameAndPath).
From reading the documentation here and some testing, it seems that the issue is actually being caused in the first iteration of the loop by wb.close, this sets wb to nothing, which then causes the error in the second iteration.
If i'm right then my question is how to "Respecify a reference for the object variable"?
Sub SaveExcels()
Dim objNS As Outlook.NameSpace: Set objNS = GetNamespace("MAPI")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Dim Item As Object
Dim objAttachments As Outlook.Attachments
For Each Item In olFolder.Items
If TypeOf Item Is Outlook.MailItem Then
Dim oMail As Outlook.MailItem: Set oMail = Item
' Check it contains an attachment
Set objAttachments = oMail.Attachments
lngCount = objAttachments.Count
' Check its from the right company
senderCheck = InStr(oMail.SenderEmailAddress, "company.com")
' Check that it is the right email type
subjectCheck = InStr(oMail.Subject, "TYPE")
' Check whether its the latest weeks data
receivedDate = DateValue(oMail.ReceivedTime)
todaysDate = DateValue(Now())
dateDifference = todaysDate - receivedDate
If lngCount > 0 And senderCheck > 0 And subjectCheck > 0 And dateDifference <= 7 Then
' Get the file name
strFile = objAttachments.Item(1).FileName
' Debug.Print strFile
strFolderpath = "D:\Users\" & Environ("Username") & "\Desktop\temp\"
' Combine with the path to the Temp folder.
strFileIncPath = strFolderpath & strFile
' Debug.Print strFile
' Save the attachment as a file.
objAttachments.Item(1).SaveAsFile strFileIncPath
' Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.NameSpace(strFolderpath).CopyHere oApp.NameSpace(strFileIncPath).Items
' Delete the zip file
Kill strFileIncPath
' Open the excel file
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
xlName = Replace(strFile, ".ZIP", "")
xlNameTemp = xlName & "_00000.xls"
xlNameAndPath = strFolderpath & xlName
Debug.Print xlNameAndPath
xlApp.Workbooks.Open strFolderpath & xlNameTemp
Dim wb As Workbook
Set wb = ActiveWorkbook
' Save as unique name and close
wb.SaveAs FileFormat:=51, FileName:=xlNameAndPath << ERROR
' Get rid of the old excel
Kill strFolderpath & xlNameTemp
' Close the workbook
wb.Close
End If
End If
Next
End Sub
I believe
Dim wb As Workbook
Set wb = xlApp.Workbooks.Open(strFolderpath & xlNameTemp)
will do the job, per the docs. (Not tested -YMMV!)
My mails in Outlook has all specific subjects. I have a Excel Sheet which has subject and Folder Name.
I have already this code from Stackoverflow
Option Explicit
Public Sub Move_Items()
'// Declare your Variables
Dim Inbox As Outlook.MAPIFolder
Dim SubFolder As Outlook.MAPIFolder
Dim olNs As Outlook.NameSpace
Dim Item As Object
Dim lngCount As Long
Dim Items As Outlook.Items
On Error GoTo MsgErr
'// Set Inbox Reference
Set olNs = Application.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
'// Loop through the Items in the folder backwards
For lngCount = Items.Count To 1 Step -1
Set Item = Items.Item(lngCount)
Debug.Print Item.Subject
If Item.Class = olMail Then
'// Set SubFolder of Inbox
Set SubFolder = Inbox.Folders("Temp")
'// Mark As Read
Item.UnRead = False
'// Move Mail Item to sub Folder
Item.Move SubFolder
End If
Next lngCount
MsgErr_Exit:
Set Inbox = Nothing
Set SubFolder = Nothing
Set olNs = Nothing
Set Item = Nothing
Exit Sub
'// Error information
MsgErr:
MsgBox "An unexpected Error has occurred." _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume MsgErr_Exit
End Sub
I want the code to read the active sheet columns, as follow:
Subject.mail folder_name
A 1
B 2
C 3
For example Mail in the Inbox with subject "A" then it has to place that mail in folder "1".
How do I loop? to look at the Sheet1 and to read to which sub folder it has to move ?
You have few options to do this, the painless one is to run Outlook VBA code from inside outlook so you don't need to go through a lot of referencing problem, but at the same time if you are insisting in having your list of subjects and folder in an Excel file, then it is better to run it from Excel, but here is the issue: You'd better not try to run the code from Excel because Microsoft is not supporting that method, so the best way is to write the code in Excel VBA, and again you can do late (runtime) binding or early binding, but I prefer early binding to use intellisence for better referencing outlook objects and avoid late binding performance and/or debugging problems.
Here is the code and how you should use it:
Go to the excel file that you have your subject and folders list or create a new one. Hit ALT+F11 to go to VBE. On the left panel (project explorer) right click and insert a module. Paste this code in there:
Option Explicit
Public Sub MoveEmailsToFolders()
'arr will be a 2D array sitting in an Excel file, 1st col=subject, 2nd col=folder name
' // Declare your Variables
Dim i As Long
Dim rowCount As Integer
Dim strSubjec As String
Dim strFolder As String
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim myFolder As Outlook.Folder
Dim Item As Object
Dim Inbox As Outlook.MAPIFolder
Dim SubFolder As Outlook.MAPIFolder
Dim lngCount As Long
Dim Items As Outlook.Items
Dim arr() As Variant 'store Excel table as an array for faster iterations
Dim WS As Worksheet
'On Error GoTo MsgErr
'Set Excel references
Set WS = ActiveSheet
If WS.ListObjects.Count = 0 Then
MsgBox "Activesheet did not have the Excel table containing Subjects and Outlook Folder Names", vbCritical, "Error"
Exit Sub
Else
arr = WS.ListObjects(1).DataBodyRange.Value
rowCount = UBound(arr, 2)
If rowCount = 0 Then
MsgBox "Excel table does not have rows.", vbCritical, "Error"
Exit Sub
End If
End If
'Set Outlook Inbox Reference
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set myFolder = olNs.GetDefaultFolder(olFolderInbox)
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
' // Loop through the Items in the folder backwards
For lngCount = Items.Count To 1 Step -1
strFolder = ""
Set Item = Items.Item(lngCount)
'Debug.Print Item.Subject
If Item.Class = olMail Then
'Determine whether subject is among the subjects in the Excel table
For i = 1 To rowCount
If arr(i, 1) = Item.Subject Then
strFolder = arr(i, 2)
'// Set SubFolder of Inbox, read the appropriate folder name from table in Excel
Set SubFolder = Inbox.Folders(strFolder)
'// Mark As Read
Item.UnRead = False
'// Move Mail Item to sub Folder
Item.Move SubFolder
Exit For
End If
Next i
End If
Next lngCount
MsgErr_Exit:
Set Inbox = Nothing
Set SubFolder = Nothing
Set olNs = Nothing
Set Item = Nothing
Exit Sub
'// Error information
MsgErr:
MsgBox "An unexpected Error has occurred." _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume MsgErr_Exit
End Sub
Set Reference:
To use outlook objects, in Excel VBE go to Tools, References and check Microsoft Outlook object library.
Set Excel Sheet:
In an Excel sheet, create a table with two columns that the first column contains email subjects and the second column contains folders to which you want those emails to be moved.
Then, insert a shape and right click on that and Assign a Macro, find the name of the macro (MoveEmailsToFolders) and click ok.
Suggestions:
You can develop the code more to disregard matchcase. To do that replace this line:
arr(i, 1) = Item.Subject
with:
Ucase(arr(i, 1)) = Ucase(Item.Subject)
Also, you can move the emails that contain the subject rather than matching an exact title, for example if an email subject had "test", or begins with "test", or ends with "test", then move it to the corresponding folder. Then, the comparison clause would be:
If arr(i, 1) Like Item.Subject & "*" Then 'begins with
If arr(i, 1) Like "*" & Item.Subject & "*" Then 'contains
If arr(i, 1) Like "*" & Item.Subject Then 'ends with
Hope this helps! Please hit the check mark to make this as the right answer to your questions if it did
I would use an explicit reference to your sheet instead of ActiveSheet unless you are actually running the Macro on a bunch of different sheets. And I'm just assuming your data is in column A and B and starts at row 2 for examples sake. This is how you would loop through your data and trying to match the subject, then move it to a folder with the name in the next column if it matches.
If Item.Class = olMail Then
For i = 2 To ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row
If ActiveSheet.Range("A" & i).Value = Item.Subject Then
'// Set SubFolder of Inbox
Set SubFolder = Inbox.Folders(ActiveSheet.Range("B" & i).Value)
'// Mark As Read
Item.UnRead = False
'// Move Mail Item to sub Folder
Item.Move SubFolder
End If
Next
End If
There are ways you could check without using a loop as well such as the Find method
Dim rnFind As Range
If Item.Class = olMail Then
Set rnFind = ActiveSheet.Range("A2", ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp)).Find(Item.Subject)
If Not rnFind Is Nothing Then
'// Set SubFolder of Inbox
Set SubFolder = Inbox.Folders(rnFind.Offset(, 1).Value)
'// Mark As Read
Item.UnRead = False
'// Move Mail Item to sub Folder
Item.Move SubFolder
End If
End If
Use Do Until IsEmpty loop, Make sure to set Excel Object Referees...
See Example on how to loop from Outlook...
Option Explicit
Public Sub Move_Items()
'// Declare your Variables
Dim Inbox As Outlook.MAPIFolder
Dim SubFolder As Outlook.MAPIFolder
Dim olNs As Outlook.NameSpace
Dim Items As Outlook.Items
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim Item As Object
Dim ItemSubject As String
Dim SubFldr As String
Dim lngCount As Long
Dim lngRow As Long
On Error GoTo MsgErr
'// Set Inbox Reference
Set olNs = Application.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
'// Excel Book Reference
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open("C:\Temp\Book1.xlsx") ' Excel Book Path
lngRow = 2 ' Start Row
With xlBook.Worksheets("Sheet1") ' Sheet Name
Do Until IsEmpty(.Cells(lngRow, 1))
ItemSubject = .Cells(lngRow, 1).Value ' Subject
SubFldr = .Cells(lngRow, 2).Value ' Folder Name
'// Loop through the Items in the folder backwards
For lngCount = Items.Count To 1 Step -1
Set Item = Items.Item(lngCount)
If Item.Class = olMail Then
If Item.Subject = ItemSubject Then
Debug.Print Item.Subject
Set SubFolder = Inbox.Folders(SubFldr) ' Set SubFolder
Debug.Print SubFolder
Item.UnRead = False ' Mark As Read
Item.Move SubFolder ' Move to sub Folder
End If
End If
Next
lngRow = lngRow + 1
Loop
End With
xlBook.Close
MsgErr_Exit:
Set Inbox = Nothing
Set SubFolder = Nothing
Set olNs = Nothing
Set Item = Nothing
Set xlApp = Nothing
Set xlBook = Nothing
Exit Sub
'// Error information
MsgErr:
MsgBox "An unexpected Error has occurred." _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume MsgErr_Exit
End Sub
I'm trying to open .msg files from a specified directory using VBA but I keep getting a runtime error.
The code i have:
Sub bla()
Dim objOL As Object
Dim Msg As Object
Set objOL = CreateObject("Outlook.Application")
inPath = "C:\Users\SiliconPlus\Desktop\Si+ Contact Lists\Contact_Si+"
thisFile = Dir(inPath & "\*.msg")
Set Msg = objOL.CreateItemFromTemplate(thisFile)
' now use msg to get at the email parts
MsgBox Msg.Subject
Set objOL = Nothing
Set Msg = Nothing
End Sub
Here is the runtime error:
Run-time error '-2147287038 (80030002)':
Cannot open file: AUTO Andy Low Yong Cheng is out of the office (returning 22 09 2014).msg.
The file may not exist, you may not have permission to open it, or it may be open in another program. Right-click the folder that contains the file, and then click properties to check your permissions for the folder.
Kenneth Li You didn't had the full path when opening the file. Try this:
Sub bla_OK()
Dim objOL As Object
Dim Msg As Object
Set objOL = CreateObject("Outlook.Application")
inPath = "C:\Users\SiliconPlus\Desktop\Si+ Contact Lists\Contact_Si+"
thisFile = Dir(inPath & "\*.msg")
'Set Msg = objOL.CreateItemFromTemplate(thisFile)
Set Msg = objOL.Session.OpenSharedItem(inPath & "\" & thisFile)
' now use msg to get at the email parts
MsgBox Msg.Subject
Set objOL = Nothing
Set Msg = Nothing
End Sub
If you get an error, try the Late Biding (Dim Msg As Object) right under the MsgBox (need to be uncommented) :
Sub Kenneth_Li()
Dim objOL As Outlook.Application
Dim Msg As Outlook.MailItem
Msgbox "If you get an error, try the Late Biding right under this (need to be uncommented)"
'Dim objOL As Object
'Dim Msg As Object
Set objOL = CreateObject("Outlook.Application")
inPath = "C:\Users\SiliconPlus\Desktop\Si+ Contact Lists\Contact_Si+"
thisFile = LCase(Dir(inPath & "\*.msg"))
Do While thisFile <> ""
'Set Msg = objOL.CreateItemFromTemplate(thisFile)
'Or
'Set Msg = objOL.OpenSharedItem(thisFile)
'Set Msg = GetNameSpace("MAPI").OpenSharedItem(thisFile)
'Eventually with Shell command (here for notepad)
'Shell "notepad " & thisFile
Set Msg = objOL.Session.OpenSharedItem(thisFile)
Msg.display
MsgBox Msg.Subject
thisFile = Dir
Loop
Set objOL = Nothing
Set Msg = Nothing
End Sub
Or you can find a nice VB solution there : http://www.mrexcel.com/forum/excel-questions/551148-open-msg-file-using-visual-basic-applications.html#post2721847
And here for more details on Shell method : http://p2p.wrox.com/access-vba/27776-how-open-msg-file-vbulletin.html#post138411
Another way is to run the file programmatically (in VBA use the Shell command). It will be opened in Outlook where you can get an active inspector window with the item opened.
You should check follow code and can modify your code
Sub CreateFromTemplate()
Dim MyItem As Outlook.MailItem
Set MyItem = Application.CreateItemFromTemplate("C:\temp\*.msg")
MyItem.Display
End Sub
Try this
Sub GetMSG()
' True includes subfolders
' False to check only listed folder
ListFilesInFolder "C:\Users\lengkgan\Desktop\Testing", True
End Sub
Sub ListFilesInFolder(SourceFolderName As String, IncludeSubfolders As Boolean)
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder, SubFolder As Scripting.Folder
Dim FileItem As Scripting.File
Dim strFile, strFileType, strAttach As String
Dim openMsg As MailItem
Dim objAttachments As Outlook.Attachments
Dim i As Long
Dim lngCount As Long
Dim strFolderpath As String
'where to save attachments
strFolderpath = "C:\Users\lengkgan\Desktop\Testing"
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
For Each FileItem In SourceFolder.Files
strFile = FileItem.Name
' This code looks at the last 4 characters in a filename
' If we wanted more than .msg, we'd use Case Select statement
strFileType = LCase$(Right$(strFile, 4))
If strFileType = ".msg" Then
Debug.Print FileItem.Path
Set openMsg = Outlook.Application.CreateItemFromTemplate(FileItem.Path)
openMsg.Display
'do whatever
Set objAttachments = openMsg.Attachments
lngCount = objAttachments.Count
If lngCount > 0 Then
For i = lngCount To 1 Step -1
' Get the file name.
strAttach = objAttachments.Item(i).Filename
' Combine with the path to the Temp folder.
strAttach = strFolderpath & strAttach
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strAttach
Next i
End If
openMsg.Close olDiscard
Set objAttachments = Nothing
Set openMsg = Nothing
' end do whatever
End If
Next FileItem
If IncludeSubfolders Then
For Each SubFolder In SourceFolder.SubFolders
ListFilesInFolder SubFolder.Path, True
Next SubFolder
End If
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Edited : How to add the reference
Click Tools > Reference.
Check the needed reference