简体   繁体   中英

How can I make my VBA Outlook script more efficient

This is my first question on StackExchange ever :-) I am Running the following script in MS Outlook VBA

Sub export()

    On Error resume Next

    Dim Ns As Outlook.NameSpace
    Dim eitem
    Dim oFile As Object
    Dim fso As Object

    Set Ns = Application.GetNamespace("MAPI")
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFile = fso.CreateTextFile("C:\Users\chakkalakka\Desktop\mails.txt")

    'Code
    For Each eitem In Ns.Session.Folders.Item(12).Items
        oFile.WriteLine eitem.SenderName & "§" & eitem.SentOnBehalfOfName & "§" & eitem.ReceivedTime
    Next

    oFile.Close
    Set Ns = Nothing
    Set fso = Nothing
    Set oFile = Nothing

    Debug.Print "Completed!"

End Sub

The script in general is working fine and the output is correct. My Problem is: I need to run this inside a folder with > 95000 items and it takes ages.

So my question is: What can I do to improve performance?

Thanks in advance for your help

The most inefficient line of code is the following one:

For Each eitem In Ns.Session.Folders.Item(12).Items

You need to break the chain of property and method calls and declare them on separate lines. So each property or method will be declared on a separate line of code. Thus, you will be able to release underlying COM objects instantly. Set a variable to Nothing in Visual Basic to release the reference to the object.

Iterating through all items in the folder is a time-consuming task. Instead, I'd suggest using the Find / FindNext or Restrict methods of the Items class to deal with items that correspond to your conditions. Read more about these methods in the following articles:

Also you may consider using the GetTable method of the Folder class which allows to obtain a Table object that contains items filtered by Filter . If Filter is a blank string or the Filter parameter is omitted, GetTable returns a Table with rows representing all the items in the Folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM