Home
FREE DOWNLOADS
VBA Tutorials
VBA Code Samples
VBA Code - Excel
VBA for Beginners
Save Time on PC
SaveTimeWebsite
Save Time News
Save Time Blog
SaveTime SiteMap
Customer Service
Gibberish

Subscribe To
This Site

XML RSS
Add to Google
Add to My Yahoo!
Add to My MSN
Add to Newsgator
Subscribe with Bloglines

VBA Coding Example

In this VBA coding example we'll take a look at how to move messages from your Inbox to a folder you choose from the Pick Folder dialog box using a string prompted for by an InputBox.

First, from outlook, press ALT + F11 to open the VBA editor. Right click on anything in the Project Explorer tree...

Insert Module


Copy/paste the following code into the new module...
Sub MovingItems()
    Dim OlApp As New Outlook.Application
    Dim NS As Outlook.NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim fldDest As Outlook.MAPIFolder
    Dim Items As Outlook.Items
    Dim Item As Object
    Dim strSearch As String
    Set NS = OlApp.GetNamespace("MAPI")
    Set Inbox = NS.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
    Set fldDest = NS.PickFolder
    strSearch = InputBox("Search in Subject")
    For Each Item In Items
        If InStr(UCase(Item.Subject), UCase(strSearch)) Then
            Item.Move fldDest
        End If
    Next
    Set NS = Nothing
    Set Inbox = Nothing
    Set Items = Nothing
    Set fldDest = Nothing
End Sub
This line will always be the same when working in Outlook...

Set NS = OlApp.GetNamespace("MAPI")

Since the search is case-sensive we'll convert both the "Item.Subject" and our "strSearch" variable to uppercase...

If InStr(UCase(Item.Subject), UCase(strSearch)) Then

In this VBA coding example we used the Item's Subject. We could have also used the Body, Item.Body.

The lines that start with "Dim" declare our variables. Since all but strSearch are Object variables, we assign their Objects to them with the Set statement. We don't do this for the OlApp variable because we dimensioned (Dim) it with the keyword "New," so this happens automatically.

The last four lines before the End Sub reclaim memory, which means that VBA is telling Windows that it is finished using the variable (which is stored in memory) and thereby Windows can now allocate the memory to something else.

The following line pops up the PickFolder dialog box...

Set fldDest = NS.PickFolder

Google

Return from VBA Coding Example to VBA Code Samples

Return to our Home page



footer for vba coding example page