Writing email messages to flat files in Outlook with VBA

Craig picture Craig · Dec 30, 2008 · Viewed 9.5k times · Source

I have written a VBA app that opens a folder in outlook and then iterates through the messages. I need to write the message bodies (with some tweaking) to a single flat file. My code is as follows...

Private Sub btnGo_Click()
    Dim objOutlook As New Outlook.Application
    Dim objNameSpace As Outlook.NameSpace
    Dim objInbox As MAPIFolder
    Dim objMail As mailItem
    Dim count As Integer

    Set objNameSpace = objOutlook.GetNamespace("MAPI")
    Set objInbox = objNameSpace.GetDefaultFolder(olFolderInbox)
    count = 0

    For Each objMail In objInbox.Items
       lblStatus.Caption = "Count: " + CStr(count)
       ProcessMailItem (objMail)
       count = count + 1
    Next objMail

  End If
End Sub

The part in question is "ProcessMailItem". As I am not overly concerned with performance at this stage so the very inefficent "open, append, close" file methodology is fine for this example.

I know I could spend some time looking up the answer with google but I checked here first and there was no good answers for this. Being a fan of Stackoverflow I hope that putting this up here will help future developers looking for answers. Thanks for your patience.

Answer

Jon Fournier picture Jon Fournier · Dec 30, 2008

You can get away with writing to a file without using any objects, just using the built in VBA file tools:

Open "C:\file.txt" for append as 1
Print #1, SomeStringVar
Close #1