Microsoft Office Tutorials and References
In Depth Information
The Nothing Keyword
VBA has a special keyword, Nothing , that indicates that an object reference does not contain
a valid reference to an object. When an object reference has been declared but not initialized,
it contains Nothing . You can also explicitly set an object reference to Nothing when you are
finished using the object or to make sure the reference does not point at a valid object:
Set objRef = Nothing
The Is Nothing operator lets you test for this value:
If objRef Is Nothing Then
‘ Actions to take if the reference is not valid.
‘ Actions to take if the reference points to a valid object.
End If
However, this technique cannot be used with many kinds of objects, including MailItem . Rather,
you must get a reference to an instance of the object using the Outlook Object Model. For example,
you cannot create a new MailItem object with the following code:
Set MyMessage = New Outlook.MailItem
You see exactly how to create references to Outlook objects throughout the chapter.
Working with Collections
Collections are an important part of Outlook macro programming. Whenever the Object Model
requires more than one of something, it uses a collection to keep track of them. For example, in
Outlook each mail folder, such as the Inbox, is represented by an object. A folder can contain any
number of email messages, and these messages are represented as a collection. Collections are
designed with built-in tools that make is easy to find an individual object in the collection or to do
something with all of the objects in the collection. Every collection has the Count property, which
tells you the number of elements in the collection.
The most common use for collections is when you want to process every item in the collection.
For example, suppose you want to write a macro that looks at every email message in the Inbox
and moves those messages from a certain sender to another folder. By looping through the
collection of email messages in this folder, the task is easily accomplished no matter how many or few
messages there are in the folder. You use the For Each...Next loop, introduced in Chapter 23,
for this purpose.
Search JabSto ::

Custom Search