Skip to content

Outlook VBA: Write to a file

May 30th, 2016 - SoftwareTutorial

Note: This is a post transferred from Laurii for historical and consolidation purposes.

I’m not a master in VB (I hate it actually) not in VBA, but it;s quicker to write something like a hack in VBA for outlook than in C#. So, here’s a tiny snapshot on how to write to a file in Outlook (my version is 2003):

Sub WriteToATextFile
    'first set a string which contains the path to the file you want to create.
    'this example creates one and stores it in the root directory
    MyFile = "c:\" & "whateveryouwant.txt"

    'set and open file for output
    fnum = FreeFile()
    Open MyFile For Output As fnum

    'write project info and then a blank line. Note the comma is required
    Write #fnum, "I wrote this"
    Write #fnum,

    'use Print when you want the string without quotation marks
    Print #fnum, "I printed this"
    Close #fnum
End Sub

This is nice and funny, but you need to pass this as a parameter to functions to ensure that writing is done properly (sometimes at least)… You can do it like this:

Sub Main()

    MyFile = "d:\" & "whateveryouwant.txt"

    'set and open file for output
    fnum = FreeFile()
    Open MyFile For Output As fnum

    'transmit the file as a parameter in a function
    WalkFolders (fnum)
    Close #fnum
    'MsgBox "Outlook Set Up Succesfully"

End Sub

Sub WalkFolders(fnum)
    'write something
    Write #fnum, "I wrote this"
End Sub

See? Easy!

Share on
Reddit
Linked in
Whatsapp

A little experiment: