Excel vba objects and methods

Excel VBA Tutorial about Object MethodsIf you’re in the process of learning Visual Basic for Applications, there are a few basic topics you need to thoroughly understand. I have explained some of these in other blog posts that you can find at the Power Spreadsheets Archive.

However, at the most basic level, the following 3 topics are perhaps the most basic things you need to learn and understand in order to start making useful things with VBA:

  1. Objects.
  2. Object properties.
  3. Object methods.

You can read some of the tutorials I’ve written about the first 2 topics here, here (for objects), and here (for properties). This blog post focuses on the third item in the list above:

Methods.

More precisely, I explain the most important aspects you need to know in order to start working with object methods in VBA. You can use the following table of contents to navigate directly to any section you’re most interested in. Make sure to read the full post in any case 😉 .

OK. Let’s go straight into the topic of today’s post and take a closer look at…

What Are Object Methods In VBA And Why Are They Important

There’s no question that knowing about VBA objects is extremely important. To achieve something of practical value, you must do something with/to the object(s) you work with.

Therefore, you must know about VBA objects in order to become a great Excel VBA programmer. However, this isn’t enough on its own…

You also need to know and understand how you can manipulate those objects. And this is where object methods and object properties come in:

Methods are the actions or operations you perform with an object (by or on the object). Properties, on the other hand, are the attributes or characteristics you can use to describe the object.

According to a common analogy (between VBA and the parts of speech in the English language), you can think of:

  • Objects as akin to nouns.
  • Properties as analogous to adjectives.
  • Methods as corresponding to verbs.

It’s not possible to communicate fluently in English by just using nouns (without also using adjectives and verbs). Similarly, you can’t build appropriate VBA applications by just using objects (without also including properties and methods).

The ability of specifying the action to be applied to an object allows you to use methods for the following 2 main purposes:

  • Purpose #1: Make an object do something.
  • Purpose #2: Modify the properties of an object. Consider (for ex.) the Range.ClearContents method. The Range.ClearContents method:
    • Clears values and formulas from the applicable cell range.
    • (Generally) Results in a change to the applicable Range.Value property (the cell range’s value).

This applies to object collections as well. The reason for this, as explained here, is that collections are themselves objects.

However, in order to ensure that you do a great job with the object methods you’ll need to use, let’s take a look at…

How To Work With Object Methods In VBA

Let’s start to take a closer look at how you structure a statement that refers to (or calls/access) object methods. For these purposes, we’ll examine the following macro (called “Delete_Inactive_Worksheets”). The purpose of this Sub procedure is to delete all worksheets except for the one that’s currently active.

Sub Delete_Inactive_Worksheets()
    Dim my_Worksheet As Worksheet
    For Each my_Worksheet In ThisWorkbook.Worksheets
        If my_Worksheet.Name <> ThisWorkbook.ActiveSheet.Name Then
            Application.DisplayAlerts = False
            my_Worksheet.Delete
            Application.DisplayAlerts = True
        End If
    Next my_Worksheet
End Sub

This Excel VBA Methods Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following screenshot shows how the VBA code of the Delete_Inactive_Worksheets macro looks like in the Visual Basic Editor:

Example macro to illustrate VBA object properties

I won’t explain this particular macro line-by-line. For purposes of this Excel tutorial, we’ll focus on the following statement:

my_Worksheet.Delete

This statement is within the If…Then statement in the macro above. The relevant row of code is underlined in the following screenshot:

Macro example with highlighted VBA object method

This simple statement is enough to illustrate the basic rule to create references to object properties in Visual Basic for Applications:

You refer to (or call/access) a method by putting together the following 3 items:

  • Item #1: Name of the relevant VBA object. In the case above, this is the object variable my_Worksheet.
  • Item #2: A dot (.).
  • Item #3: Name of the method. In the case above, this is “Delete” or, more precisely, the Worksheet.Delete method.

In fact, most procedures have a number of lines following this basic structure:

Object.Method

Under this (basic) statement structure, the item after the dot (Method in the case above) acts on/with the item before the dot (Object in the case above).

One final note before we move on to the next section:

Note how, above, I mention specifically the Worksheet.Delete method instead of simply referring to the Delete method. This is important because a method may behave differently depending on the object it works with.

For example, when it comes to the Delete method, its syntax and precise behavior can be slightly different depending on whether it is applied to a Worksheet object (Worksheet.Delete method) or a Range object (Range.Delete method). Yes, in both cases the end result is that Excel deletes the relevant object. However:

  • When applied to a Range object, the Delete method has an extra argument (I explain method arguments below) which allows you to determine how Excel shifts the cells that replace any deleted cells.
  • When working with a Worksheet object, the method displays (by default) a dialog box asking you to confirm the worksheet deletion.

As you continue to work with Excel and Visual Basic for Applications, these nuances will become clearer. However, you may want to confirm that your choice of VBA object methods actually carry out the actions you want them to when working with the VBA objects you’re working with.

How To Work With The Arguments (Or Parameters) Of Object Methods In VBA

Arguments (also known as parameters) are, generally, what allows you to further determine the action that a method performs with an object.

In other words: Parameters allow you to determine “how” the action/method is carried out.

Going back to the parallel between VBA and the parts of speech of regular English, you can think of method arguments as being comparable to adverbs.

Some, but not all, object methods in VBA take arguments. Arguments can be mandatory or optional.

The topic of arguments is, actually, not as easy as you may think at first glance. In this section, we take a look at the most important aspects you must know in connection with this topic.

For purposes of illustrating how to work with the arguments of object methods in VBA, I make reference to the following simple macro (called “Copy_Main_Worksheet”). The Copy_Main_Worksheet macro (i) copies the worksheet called “Object Methods in VBA” and (ii) pastes the copy after the worksheet named “Sheet1”.

Sub Copy_Main_Worksheet()
    Worksheets("Object Methods In VBA").Copy After:=Worksheets("Sheet1")
End Sub

This Excel VBA Methods Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following image shows the VBA code of the Copy_Main_Worksheet within the Visual Basic Editor:

Example macro with object property argument

Let’s focus on the relevant statement of this macro, which is underlined in the image below:

VBA code example with object method arguments

You already know how to refer to object methods, the topic I explain above. Therefore, you probably identify the first part of the statement (“Worksheets(“Object Methods In VBA”).Copy”) as a reference that is divided in the following 3 items:

  • Item #1: “Worksheets(“Object Methods In VBA”)” makes reference to the Worksheet object named “Object Methods In VBA”.
  • Item #2: A dot (.) separates part #1 above from part #3 below.
  • Item #3: “Copy” makes reference to the Worksheet.Copy method.

The second part of the statement (“After:=Worksheets(“Sheet1″)”) is the part that sets the relevant method parameters. More precisely, it determines that the copied worksheet is placed after the sheet called “Sheet1”.

The Worksheet.Copy method has 2 optional but exclusive (you can only specify one of them) parameters:

  • Optional Parameter #1: “Before”, which determines which is the sheet in front of (or before) which the copied worksheet is placed.
  • Optional Parameter #2: “After”, which sets what is the sheet after which the copied worksheet is placed.
    • This is the parameter I use in this example. In other words: The copied worksheet is placed after “Sheet1”.

The following image breaks down the statement in the parts and items I explain above:

Macro explaining method arguments

This way of setting method parameters (which I explain below) isn’t the only syntax you can use. More precisely:

There are a few ways in which you can work with the arguments of object methods. In order to understand this better, let’s take a look at the most important ways in which you can specify the arguments for an object method in VBA:

Option #1: Basic Syntax To Specify Object Method Arguments

The Copy_Main_Worksheet macro that appears above doesn’t use the most basic form of syntax to specify method arguments. Although…

After going through this section you’ll probably:

  • Think that the basic syntax isn’t really that basic.
  • Understand why I use another syntax (which I explain below) in the version of the Copy_Main_Worksheet macro that appears above.

The following version of the Copy_Main_Worksheet macro uses the basic syntax to set the arguments of an object method. Notice the difference between both versions when it comes to referring to the method parameters.

Example of basic syntax VBA method property

I explain why there’s a comma (,) at the beginning of this part of the statement below. Excluding that comma, the basic syntax to specify arguments is relative straightforward:

Object.Method Argument_Value

In other words, to determine an argument for a VBA object method, you must:

  • Step #1: Refer to the object method appropriately by following the basic syntax explained above.
    • In the case above, this is “Worksheets(“Object Methods In VBA”).Copy”.
  • Step #2: Place a space ( ) after the name of the method.
  • Step #3: Place the relevant argument values.
    • In the example above, this is “, Worksheets(“Sheet1″)”.

You already know what “Worksheets(“Sheet1″)” does: It’s the After parameter that determines that the copied worksheet is placed after “Sheet1”.

That leaves the comma (,) at the beginning.

Syntax for several VBA object methods

This comma (,) appears because of the following 3 syntax rules:

  • When using more than 1 argument, use commas (,) to separate them.
  • When working with unnamed arguments, enter arguments in their default order.
  • When working with optional (and unnamed) arguments, use commas (,) to create blank placeholders for omitted arguments.
    • There are some cases where you don’t need to create placeholders for omitted arguments (for ex., when the argument you omit is at the end of the argument list).

In this case, the Worksheet.Copy method has 2 optional but exclusive arguments: Before and After. The Copy_Main_Worksheet uses only the second argument (After). Therefore, the VBA code that appears above includes a comma (,) and a blank placeholder for the unused Before argument.

As you see, the “basic” syntax to specify the arguments of a method isn’t that readable. And this was a single (and quite straightforward statement)…

Just imagine how it would be to work in a large and complex VBA application that uses this syntax and has plenty of methods with optional arguments and blank placeholders 😕 .

Fortunately, there is a second way in which you can set the parameters that clarify the action to be taken by a particular method. This is the syntax used in the original version of the Copy_Main_Worksheet macro above. Let’s take a look at it:

Option #2: Named Arguments

As implied by the description of this way of referring to the arguments of VBA object properties, you use the actual name of the argument when specifying it. More precisely, you use the following syntax:

Object.Method Argument_Name:=Argument_Value

In other words, when using named arguments you proceed as follows:

  • Step #1: Repeat the first 2 steps described above where I describe the basic syntax to specify the arguments of object methods.
    • In other words: (i) refer to the object method appropriately, and (ii) place a space after the name of the method.
  • Step #2: Write the (official) name of the argument.
  • Step #3: Place a colon and an equal sign (:=).
  • Step #4: Set the relevant argument value.

This is the syntax that I use in the first version of the Copy_Main_Worksheet macro that appears above.

Named argument for VBA object method

When you use named arguments for object methods in VBA, you don’t have to use any placeholder for the optional arguments that you don’t use. Therefore, in this case, there’s no placeholder at all for the missing Before argument of the Worksheets.Copy method.

You don’t need to use named arguments (is optional) and can get away with using the basic syntax described above. However, using named arguments has a few advantages over not using them, particularly the fact that named arguments improve the readability of your VBA code.

You can (theoretically):

  • Start specifying arguments using the basic syntax described above; and
  • Switch to named arguments at some point in the middle of the argument list. Once you include a named method argument, the remaining method arguments must (also) be named.

However, I don’t necessarily recommend this syntax.

Even though you can switch from non-named arguments to named arguments in the middle of a statement, you can’t do the opposite. In other words, you can’t start specifying parameters using named arguments and then switch to the basic syntax. Once you use named arguments once, you must continue working with named parameters for that particular line.

After comparing both syntax options for setting VBA object method parameters, you’ll probably agree that using named arguments is (as a general rule) a better practice.

Before we finish the topic of specifying arguments for object methods in VBA, let’s take a look at 2 additional clarifications regarding the syntax you use when setting VBA method arguments:

Referring To The Arguments Of Methods That Return A Value And Working With Default Argument Values

When working with methods that return a value or create new objects, you must (generally) wrap the arguments in parentheses. In such cases, as long as the arguments are within the parentheses, you can continue to use either of the 2 syntax options that I describe above (unnamed or named arguments).

Finally, note that several objects within Visual Basic for Applications have a particular default method value. You don’t necessarily have to provide a method value in such cases. This also applies to those methods that take more than 1 argument: some arguments may have default values while other don’t.

How To Access The Methods Of A Particular Object

A single object can have more than 1 associated method. In fact:

  • Some VBA objects have several dozen methods.
  • The Excel VBA Object Model contains thousands of methods.

But don’t feel overwhelmed!

In practice, you’re likely to work with a relatively small amount of VBA object methods over and over again. This is partly due to the fact that a single method can be associated to several VBA objects.

In other words: You’re unlikely to (in practice) work with certain methods.

However, it’s quite likely that (from time to time) you’ll need to search for a particular method while working with macros. Therefore, let’s take a look at some of the most common strategies you can use to find out the best VBA object method to achieve your goals in a particular situation.

In addition to the 3 strategies I explain below, you can also use the macro recorder to get some guidance about the objects, properties and methods you need.

Strategy #1: How To Make The Visual Basic Editor Display A List Of Methods

This is probably the easiest and most convenient way to explore the properties available for a particular VBA object. However, it only works if the Auto List Members setting of your Visual Basic Editor is enabled. In case you don’t have this setting enabled, I explain how to do it in this Excel tutorial.

In order to understand how you can make the VBE display a list of available methods, let’s go back to the code for the Delete_Inactive_Worksheets. More particularly, let’s assume that you’re typing the statement “my_Worksheet.Delete” (which I explain above) and you’re standing at the point where we must type the dot.

VBA code before VBE displays methods

Once you type the dot, the VBE displays a list of items that can be associated with that particular object. Therefore, in the case above, once you type the dot that follows my_Worksheet, the following list is shown:

VBA object method list displayed by VBE

This gives you a great idea of the properties and methods that you can use when working with a particular object. For example, if you scroll down enough, you can find the Delete method. This is the appropriate method to complete the statement above.

Delete method in list within VBE

In order to be able to take advantage of this setting, your Visual Basic Editor must have the Auto List Members setting option enabled.

Strategy #2: Use The Object Browser

As explained by Chandoo (in the webpage I link to above), the Object Browser is a “helpful screen” that allows you to browse and understand VBA objects, properties and methods.

You can use the Object Browser to obtain all the available properties and methods for a particular object in 3 simple steps:

Step #1: Open The Object Browser

There are a few ways to access the Object Browser from within the Visual Basic Editor:

Step #2: Select The Excel Library

The drop-down list that appears on the top left corner of the Visual Basic Editor (“<All Libraries>”) displays all the object libraries that are available. Click on this drop-down menu and select Excel.

Select Excel library in Object Browser

Step #3: Select The Relevant Object Class

The Object Browser is divided in 2 sections:

  • Left section: Lists all the Excel objects.
  • Right section: Displays all the properties and methods that are available for the object that is currently selected on the left.

Therefore, in order to access the VBA methods of a particular object, search the object you want to explore on the left side of the Object Browser and click on it.

For example, in the case of sample macros used throughout this Excel tutorial, it’s interesting to see what happens when clicking on “Worksheet”. As you can see in the image below, the Object Browser displays a list of its members. This list includes both the Copy and Delete methods used by the Copy_Main_Worksheet and Delete_Inactive_Worksheets macro (respectively).

Methods available for Worksheet object in VBA

Strategy #3: Visit Microsoft’s Official Documentation

Microsoft’s Official Documentation has a massive amount of content regarding VBA objects and methods (among others).

One of the things you can use Microsoft’s Official Documentation for, is to get a list of all the methods that are available for a particular VBA object. To do this, simply follow these 4 easy steps:

Step #1: Type The Name Of An Object In The Visual Basic Editor

As an example, let’s go back to the Copy_Main_Worksheets used as an example above. Assume that you’re typing the only statement of this Sub procedure. Therefore, you type the relevant object which, in this case, is “Worksheets(“Object Methods In VBA”)”.

Example of object within macro

However, now that you’ve identified the VBA object, you want to see which methods can be used on that particular object.

Step #2: Place The Cursor On The Object

In the case above you can, for example, place the cursor within the word “Worksheets”, as shown below:

Cursor on object within VBE

Step #3: Press The F1 Key

F1 is the keyboard shortcut for opening the help system. In other words, this keyboard shortcut generally should either:

  • Take you to the relevant page within Microsoft’s Official Documentation; or
  • Ask you to confirm what the topic you want to help on is. This is the case, generally, when the Visual Basic Editor finds multiple instances of the word that you’ve selected.

In this particular case, once I press the F1 key, I’m led to the page about the Application.Worksheets property within the Microsoft Dev Center.

Help for VBE in MSDN

Step #4: Navigate To The Methods Of The Relevant Object

In some cases (such as the example above), you may need to do some navigation before you actually get to the appropriate object. The reason for this is that, most objects within VBA are accessed by using a property.

For example in the case above, the Application.Worksheets property is used to return a Worksheet object. Therefore, we’re originally taken to the webpage belonging to this particular property.

However, this navigation is usually not very complicated. In the case of the Application.Worksheets property, notice how Microsoft’s Official Documentation immediately explains that the property returns a collection (which is an object itself) representing worksheets. It also includes a link leading to the Sheet object (see image below).

Example of page in MSDN

In turn, the page covering the Sheets object explains how this collection “can contain Chart or Worksheet objects”. The website, again, displays a conspicuous link that you can click to get to the Worksheets object.

Example of MSDN website

In the case above, it took a little bit longer than usual to get to the appropriate page. However, once you’re in the page that makes reference to the relevant object, you can get Microsoft’s Official Documentation to show you all the available methods by expanding the list that appears on the left side of the page.

Methods in Microsoft Developer Network

In the case above, one of those available methods is indeed the Worksheet.Copy method used by the Copy_Main_Worksheet sample macro.

Access Worksheet.Copy method in MSDN

Conclusion

I mentioned at the beginning of this blog post that having a good understanding about VBA objects, properties and methods is essential in order to do any meaningful work with Visual Basic for Applications. This Excel tutorial has provided you with the fundamental knowledge you need in order to start using methods when coding in VBA. Among other topics, we’ve covered:

  • What are object methods in VBA, and why are they important.
  • How do you create references for a method.
  • How can you set the parameters or arguments of a particular method.
  • 3 different strategies you can use to find out what are the properties you can use when working with a particular VBA object.

“High aims form high characters, and great objects bring out great minds” – Tryon Edwards

A Quick Guide to VBA Objects

Task Examples
Declare and Create Dim coll As New Collection
Dim o As New Class1
Declare Only Dim coll As Collection
Dim o As Class1
Create at run time Set coll = New Collection
Set o = New Class1
Assign to Excel Object Dim wk As Workbook
Set wk = Workbooks(«book1.xlsx»)
Assign using CreateObject Dim dict As Object
Set dict = CreateObject(«Scripting.Dictionary»)
Assign to existing object Dim coll1 As New Collection
Dim coll2 As Collection
Set coll2 = coll1
Return from Function Function GetCollection() As Collection

    Dim coll As New Collection
    Set GetCollection = coll

End Function

Receive from Function Dim coll As Collection
Set coll = GetCollection

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba objects video

Introduction

If you are serious about learning VBA then it is important to understand VBA Objects. Using objects is not that difficult. In fact, they make your life much easier.

In this post, you will see how VBA makes brilliant use of objects. How objects such as Collections, Workbooks and Worksheets save you much complexity, time and effort.

In my next post, I will cover creating objects using Class Modules. However, before you create your own it is vital that you understand exactly what they are and why you need them.

So grab your favourite beverage and take a journey into the fascinating world of VBA objects.

What is a VBA Object?

To understand what an object is, we must first look at simple variables. In VBA we have basic data types such as string, integers, double and date.

 
We use these data types when we are creating a variable e.g.

Dim Score As Long, Price As Double
Dim Firstname As String, Startdate As Date

Score = 45
Price = 24.55
Firstname = "John"
Startdate = #12/12/2016#

 
Basic VBA variables have only one purpose. To store a value while our application is running. We either put a value in the variable or read a value from the variable.

Dim Marks As Long

' Store value in Marks
Marks = 90
Marks = 34 + 44
Marks = Range("A1")

' Read value from Marks
Range("B2") = Marks
Debug.Print Marks

 
In VBA we have a Collection which we use to store groups of items. The following code shows an example of using a Collection in VBA

' https://excelmacromastery.com/
Sub UseCollection()
    
    Dim collFruit As New Collection
    
    ' Add item to the collection
    collFruit.Add "Apple"
    collFruit.Add "Pear"
    
    ' Get the number of items in the collection
    Dim lTotal As Long
    lTotal = collFruit.Count    
   
End Sub

 
The Collection is an example of an object. It is more than a variable. That is, it does more than storing a piece of data. We can add items, remove items and get the number of items.

Definition of a VBA Object: An object is a grouping of data and procedures(i.e. Functions and Subs). The procedures are used to perform some task related to the data.

In the Collection the data is the group of the items it stores. The procedures such as Add, Remove, Count then act on this data.

In the Worksheet object, the main data item is the worksheet and all the procedures perform actions related to the worksheet.

 
VBA Objects

Why VBA Uses Objects

An object is used to represent real world or computer based items.

The major benefit of an object is that it hides the implementation details. Take the VBA Collection we looked at above. It is doing some complicated stuff. When an item is added it must allocate memory, add the item, update the item count and so on.

We don’t know how it is doing this and we don’t need to know. All that we need to know is when we use Add it will add the item, Remove will remove the item and Count will give the number of items.

Using objects allows us to build our applications as blocks. Building it this way means you can work on one part without affecting other parts of your application. It also makes it easier to add items to an application. For example, a Collection can be added to any VBA application. It is not affected in any way by the existing code and in turn it will not affect the existing code.

A Real World Analogy

Looking at a real-world example can often be a good way to understand concepts.

Take a car with a combustion engine. When you are driving your car, a lot of complex stuff is happening. For example, fuel gets injected, compressed and ignited leading to combustion. This then causes the wheels of your car to turn.

VBA Object Car

A nice looking combustion engine | © BigStockPhoto.com

 
The details of how this happens are hidden from you. All you expect is that turning the key will start the car, pressing the accelerator will speed it up and pressing the brake will slow it down and so on.

Think of how great your code would be if it was full of these type of objects. Self-contained and dedicated to performing one set of tasks really well. It would make building your applications so much easier.

Object Components

There are three main items that an object can have. These are

  1. Properties – These are used to set or retrieve a value.
  2. Methods – These are function or subs that perform some task on the objects data.
  3. Events – These are function or subs that are triggered when a given event occurs

 
If you look in the Object Browser(F2) or use Intellisense you will notice different icons beside the members of an object. For example, the screenshot below shows the first three members of the Worksheet object

VBA Objects

 
What these icons mean is as follows

VBA Object Icons

 
 
Let’s take a look at the first three members of the worksheet.

It has an Activate method which we can use to make worksheet active.
It has an Activate event which is triggered when the worksheet is activated.
The Application property allows us to reference the application(i.e. Excel).

' Prints "Microsoft Excel"
Debug.Print Sheet1.Application.Name

' Prints the worksheet name
Debug.Print Sheet1.Name

 
In the next sections we will look at each of these components in more detail.
 

Object Properties

An object property allows us to read a value from the object or write a value to the object. We read and write to a property the same way we read and write to a variable.

' Set the name 
sheet1.Name = "Accounts"

' Get the name
sName = sheet1.Name

 
A property can be read-only which means we can read the value but we cannot update the value.

In the VBA Range, Address is a read-only property

' The address property of range
Debug.Print Sheet1.Range("A1").Address

 
The workbook property Fullname is also a read-only property

' The Fullname property of the Workbook object
sFile = ThisWorkbook.Fullname

 
Properties can also Set and Get objects. For example, the Worksheet has a UsedRange property that return a Range object

Set rg = Sheet1.UsedRange

 
You will notice we used the Set keyword here. We will be looking at this in detail later in the post.

Object Methods

A method is a Sub or a Function. For example, Add is a method of the Collection

' Collection Add method
Coll.Add "Apple"

 
Methods are used to perform some action to do with the object data. With a Collection, the main data is the group of items we are storing. You can see that the Add, Remove and Count methods all perform some action relating to this data.

Another example of a method is the Workbook SaveAs method

Dim wk As Workbook
Set wk = Workbooks.Open "C:DocsAccounts.xlsx"
wk.SaveAs "C:DocsAccounts_Archived.xlsx"

 
and the Worksheets Protect and Copy methods

sheet1.Protect "MyPassword"
Sheet1.Copy Before:=Sheet2

Object Events

Visual Basic is an event-driven language. What this means is that the code runs when an event occurs. Common events are button clicks, workbook Open, worksheet Activate etc.

In the code below we display a message each time Sheet1 is activated by the user. This code must be placed in the worksheet module of Sheet1.
 

Private Sub Worksheet_Activate()
    MsgBox "Sheet1 has been activated."
End Sub

 
Now that we know the parts of the VBA object let’s look at how we use an object in our code.

Creating a VBA Object

In VBA, our code must “Create” an object before we can use it. We create an object using the New keyword.

If we try to use an object before it is created we will get an error. For example, take a look at the code below

Dim coll As Collection

coll.Add "Apple"

 
When we reach the Add line no Collection has been created.

VBA Object nothing

 
If we try to run this line we get the following error

VBA Object Variable

 
There are three steps to creating a VBA object

  1. Declare the variable.
  2. Create a new object.
  3. Assign the variable to the object.

 
We can perform these steps in one line using Dim and New together. Alternatively, we can declare the variable in one line and then create and assign the object in another line using Set.

Let’s take a look at both of these techniques.

Using Dim with New

When we use Dim and New together they declare, create and assign all in one line.

' Declare, Create and Assign
Dim coll As New Collection

 
Using code like does not provide much flexibility. It will always create exactly one Collection when we run our code.

In the next section we will look at Set. This allows us to create objects based on conditions and without having to declare a variable for each new object.

Using Set with New

We can declare an object variable in one line and then we can use Set to create and assign the object on another line. This provides us with a lot of flexibility.

In the code below we declare the object variable using Dim. We then create and assign it using the Set keyword.

' Declare
Dim coll As Collection
' Create and Assign
Set coll = New Collection

 
We use Set in this way when the number of objects can vary. Using Set allows us to create multiple objects. In other words, we can create objects as we need them. We can’t do this using Dim and New.

We can also use conditions to determine if we need to create an object e.g.

Dim coll As Collection

' Only create collection if cell has data
If Range("A1") <> "" Then
    Set coll = New Collection
End If

 
Later in this post we will see some examples of using Set to create objects.

Subtle Differences of Dim Versus Set

There are some subtle differences between using New with Set and using New with Dim.
When we use New with Dim, VBA does not create the object until the first time we use it.

In the following code, the collection will not be created until we reach the line that adds “Pear”.

Dim coll As New Collection

' Collection is created on this line
coll.Add "Pear"

 
If you put a breakpoint on the Add line and check the variable value you will see the following message

Object variable or With block variable not set

When the Add line runs, the Collection will be created and the variable will now show a Collection with one item.

The reason for this is as follows. A Dim statement is different to other VBA lines of code. When VBA reaches a Sub/Function it looks at the Dim statements first. It allocates memory based on the items in the Dim statements. It is not in a position to run any code at this point.

Creating an object requires more than just allocating memory. It can involve code being executed. So VBA must wait until the code in the Sub is running before it can create the object.

Using Set with New is different in this regard to using Dim with New. The Set line is used by VBA when the code is running so VBA creates the object as soon as we use Set and New e.g.

Dim coll As Collection

' Collection is created on this line
Set coll = New Collection

coll.Add "Pear"

 
There is another subtlety to keep in mind using New. If we set the object variable to Nothing and then use it again, VBA will automatically create a new object e.g.

' https://excelmacromastery.com/
Sub EmptyColl2()
 
    ' Create collection and add items
    Dim coll As New Collection
 
    ' add items here
    coll.Add "Apple"
 
    ' Empty collection
    Set coll = Nothing
 
    ' VBA automatically creates a new object
    coll.Add "Pear"
 
End Sub

 
If we used Set in the above code to create the new Collection then the “Add Pear” line would cause an error.

When New Is Not Required

You may have noticed some objects don’t use the New keyword.

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Sheet1")
Dim wk As Workbook
Set wk = Workbooks.Open("C:DocsAccounts.xlsx")

When a workbook, is opened or created, VBA automatically creates the VBA object for it. It also creates the worksheet object for each worksheet in that workbook.

Conversely, when we close the workbook VBA will automatically delete the VBA objects associated with it.

This is great news. VBA is doing all the work for us. So when we use Workbooks.Open, VBA opens the file and creates the workbook object for the workbook.

An important point to remember is that there is only one object for each workbook. If you use different variables to reference the workbook they are all referring to the same object e.g.

Dim wk1 As Workbook
Set wk1 = Workbooks.Open("C:DocsAccounts.xlsx")

Dim wk2 As Workbook
Set wk2 = Workbooks("Accounts.xlsx")

Dim wk3 As Workbook
Set wk3 = wk2

We will look at this in more detail in the VBA Objects in Memory section below.

Using CreateObject

There are some very useful libaries that are not part of Excel VBA. These include the Dictionary, Database objects, Outlook VBA objects, Word VBA objects and so on.

These are written using COM interfaces. The beauty of COM is that we can easily use these libraries in our projects.

If we add a reference to the library we create the object in the normal way.

' Select Tools->References and place a check 
' beside "Microsoft Scripting Runtime"
Dim dict As New Scripting.Dictionary

 
If we don’t use a reference we can create the object at run time using CreateObject.

Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

 
The first method is referred to as Early Binding and the second is referred to as Late Binding(see Early versus Late Binding) for more details.

Assigning VBA Objects

We can assign basic variables using the Let keyword.

Dim sText As String, lValue As Long

Let sText = "Hello World"
Let lValue = 7

 
The Let keyword is optional so nobody actually uses it. However, it is important to understand what it is used for.

sText = "Hello World"
lValue = 7

 
When we assign a value to a property we are using the Let Property

' Both lines do the same thing
sheet1.Name = "Data"
Let sheet1.Name = "Data"

 
When we assign an object variable we use the Set keyword instead of the Let keyword. When I use “object variable” I mean any variable that isn’t a basic variable such as a string, long or double etc..

' wk is the object variable
Dim wk As Worksheet
Set wk = ThisWorkbook.Worksheets(1)

' coll1 is the object variable
Dim coll1 As New Collection
coll1.Add "Apple"

' coll2 is the object variable
Dim coll2 As Collection
Set coll2 = coll1

 
Using the Set keyword is mandatory. If we forget to use Set we will get the error below

coll2 = coll1

 
VBA Set

 
It may look like Let and Set are doing the same thing. But they are actually doing different things:

  • Let stores a value
  • Set stores an address

 
To understand more about this we need to take a peek(pun intended:-)) into memory.

VBA Objects in Memory

“Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it” – Alan Perlis

 
To understand what New and Set are doing we need to understand how variables are represented in memory.

When we declare variables, VBA creates a slot for them in memory. You can think of the slot as an Excel cell in memory.

Dim X As long, Y As Long

 
VBA Set Memory

 
When we assign values to these variables, VBA places the new values in the appropriate slots.

X = 25
Y = 12

 
VBA Basic Memory

 
We saw the following line of code earlier in this post

Dim coll As New Collection
 

 
This line creates the object in memory. However, it doesn’t store this object in the variable. It

stores the address of the object

in the variable. In programming, this is known as a Pointer.

VBA Objects in Memory

Because VBA handles this seamlessly it can seem as if the object variable and the object are the same thing. Once we understand they are different it is much easier to understand what Set is actually doing.

How Set Works

Take a look at the following code

Dim coll1 As New Collection
Dim coll2 As Collection

Set coll2 = coll1

Only one Collection has been created here. So coll1 and coll2 refer to the same Collection.

In this code, coll1 contains the address of the newly created Collection.

When we use Set we are copying the address from coll1 to coll2. So now they are both “pointing” to the same Collection in memory.

 
VBA Objects in Memory

 
Earlier in the post we looked at Workbook variables. Let’s have a look at this code again

Dim wk1 As Workbook
Set wk1 = Workbooks.Open("C:DocsAccounts.xlsx")

Dim wk2 As Workbook
Set wk2 = Workbooks("Accounts.xlsx")

Dim wk3 As Workbook
Set wk3 = Workbooks(2)

When we open the workbook Accounts.xlsx, VBA creates an object for this workbook. When we assign the workbook variables in the code above, VBA places the address of the workbook object in the variable.

In this code example, the three variables are all referring to the same workbook object.

VBA Workbook Object

If we use code like the following

wk1.SaveAs "C:TempNewName.xlsx"

VBA uses the address in wk1 to determine the workbook object to use. It does this seamlessly so when we use a workbook variable it looks like we are referring directly to the object.

To sum up what we have learned in this section:

  • Let writes a value to a basic variable
  • Set writes an address to an object variable

Objects and Procedures

In VBA we can refer to Functions and Subs as procedures. When we pass an object to a procedure only the address passed.

When we pass an object from a Function(Subs cannot return anything) only the address of the object is passed back.

In the code below we have one collection. It is the address that gets passed to and from the function.

' https://excelmacromastery.com/
Sub TestProc()
    
    ' Create collection
    Dim coll1 As New Collection
    coll1.Add "Apple"
    coll1.Add "Orange"

    Dim coll2 As Collection
    ' UseCollection passes address back to coll2
    Set coll2 = UseCollection(coll1)

End Sub

' Address of collection passed to function
Function UseCollection(coll As Collection) _
                        As Collection
    Set UseCollection = coll
End Function

Using ByRef and ByVal

When we pass a simple variable to a procedure we can pass using ByRef or ByVal.

ByRef means we are passing the address of the variable. If the variable changes in the procedure the original will also be changed.
ByVal means we are creating a copy of the variable. If the variable changes in the procedure the original will not be changed.

' Pass by value
Sub PassByVal(ByVal val As Long)

' Pass by reference
Sub PassByRef(ByRef val As Long)
Sub PassByRef(val As Long)

 
Most of the time it is a good idea to use ByVal because it prevents the variable being accidentally changed in a procedure.

When we pass a Collection to a procedure, we are always passing the address of the Collection.

ByRef and ByVal only affect the object variable. They do not affect the object!

What this means is that if we change the object in the procedure it will be changed outside it – this is regardless of whether you use ByVal or ByRef.

For example, in the code below we have two procedures that change the Collection. One uses ByRef and one uses ByVal. In both cases the Collection has changed when we return to the TestProcs Sub

' https://excelmacromastery.com/
Sub TestProcs()
    Dim c As New Collection
    c.Add "Apple"
    
    PassByVal c
    ' Prints Pear
    Debug.Print c(1)
    
    PassByRef c
    ' Prints Plum
    Debug.Print c(1)
   
End Sub

' Pass by value
Sub PassByVal(ByVal coll As Collection)
    ' Remove current fruit and add Pear
    coll.Remove (1)
    coll.Add "Pear"
End Sub

' Pass by reference
Sub PassByRef(ByRef coll As Collection)
    ' Remove current fruit and add Plum
    coll.Remove (1)
    coll.Add "Plum"
End Sub

Let’s look at a second example. Here we are setting the object variable to “point” to a new Collection. In this example, we get different results from ByVal and ByRef.

In the PassByVal Sub, a copy of the original object variable is created. So it is this copy that points to the new Collection. So our original object variable is not affected.

In the PassByRef Sub we are using the same object variable so when we point to the New Collection, our original object variable is now pointing to the new collection.

' https://excelmacromastery.com/
Sub TestProcs()

    Dim c As New Collection
    c.Add "Apple"
    
    PassByVal c
    ' Prints Apple as c pointing to same collection
    Debug.Print c(1)
    
    PassByRef c
    ' Prints Plum as c pointing to new Collecton
    Debug.Print c(1)

End Sub

' Pass by value
Sub PassByVal(ByVal coll As Collection)
    Set coll = New Collection
    coll.Add "Orange"
End Sub

' Pass by reference
Sub PassByRef(ByRef coll As Collection)
    Set coll = New Collection
    coll.Add "Plum"
End Sub

Why VBA Uses Pointers

You may be wondering why VBA uses pointers. The reason is that it is much more efficient.

Imagine you had a Collection with 50000 entries. Think how inefficient it would be to create multiple copies of this Collection when your application was running.

Think of it like a library which is a real world collection of books. We can put the Library address in directories, newspapers etc. A person simply uses the address to go to the Library and add and remove books.

There is one Libary and the address is passed around to anyone who needs to use it.If we wanted a second library we would create a new library. It would have a different address which we could also pass around.

VBA Object - Library

© BigStockPhoto.com

Running a Simple Memory Experiment

To demonstrate what we have been discussing, let’s look at a code example. The code below uses

  • VarPtr to give the memory address of the variable
  • ObjPtr to give the memory address of the object

 
The memory address is simply a long integer and it’s value is not important. But what is interesting is when we compare the addresses.

' https://excelmacromastery.com/
Sub Memory()

    Dim coll1 As New Collection
    Dim coll2 As Collection
    
    Set coll2 = coll1
    
    ' Get address of the variables Coll1 and Coll2
    Dim addrColl1 As Long, addrColl2 As Long
    addrColl1 = VarPtr(coll1)
    addrColl2 = VarPtr(coll2)
    
    Debug.Print "Address of the variable coll1 is " & addrColl1
    Debug.Print "Address of the variable coll2 is " & addrColl2
    
    ' Get address of the Collection they point to
    Dim addrCollection1 As Long, addrCollection2 As Long
    addrCollection1 = ObjPtr(coll1)
    addrCollection2 = ObjPtr(coll2)
    
    Debug.Print "Address coll1 collection is " & addrCollection1
    Debug.Print "Address coll2 collection is " & addrCollection2

End Sub

 
Note: Use LongPtr instead of Long if you are using a 64 bit version of Excel.

When you run the code you will get a result like this:

Address of the variable coll1 is 29356848
Address of the variable coll2 is 29356844
Address coll1 collection is 663634280
Address coll2 collection is 663634280

 
you will notice

  • The memory addresses will be different each time you run.
  • The address of the coll1 Collection and the coll2 Collection will always be the same.
  • The address of the coll1 variable and the coll2 variable will always be different.

 
This shows that we have two different variables which contain the address of the same Collection.

Cleaning Up Memory

So what happens if we set a variable to a New object multiple times? In the code below we use Set and New twice for the variable coll

Dim coll As Collection

Set coll = New Collection
coll.Add "Apple"

' Create a new collection and point coll to it
Set coll = New Collection

 
In this example, we created two new Collections in memory. When we created the second collection we set coll to refer to it. This means it no longer refers to the first collection. In fact, nothing is referring to the first Collection and we have no way of accessing it.

In some languages(looking at you C++) this would be a memory leak. In VBA however, this memory will be cleaned up automatically. This is known as Garbage Collection.

Let me clarify this point. If an object has no variable referring to it, VBA will automatically delete the object in memory. In the above code, our Collection with “Apple” will be deleted when coll “points” to a new Collection.

Clean Up Example

If you want to see this for yourself then try the following.

Create a class module, call it clsCustomer and add the following code.

Public Firstname As String

Private Sub Class_Terminate()
    MsgBox "Customer " & Firstname & " is being deleted."
End Sub

 
Class_Terminate is called when an object is being deleted. By placing a message box in this event we can see exactly when it occurs.

Step through the following code using F8. When you pass the Set oCust = New clsCustomer line you will get a message saying the Jack was deleted.When you exit the function you will get the message saying Jill was deleted.

' https://excelmacromastery.com/
Sub TestCleanUp()
    
    Dim oCust As New clsCustomer
    oCust.Firstname = "Jack"
    
    ' Jack will be deleted after this line
    Set oCust = New clsCustomer
    oCust.Firstname = "Jill"
    
End Sub

 
VBA automatically deletes objects when they go out of scope. This means if you declare them in a Sub/Function they will go out of scope when the Function ends.

Setting Objects to Nothing

In code examples you may see code like

Set coll = Nothing

 
A question that is often asked is “Do we need to Set variables to Nothing when we are finished with them?”. The answer is most of the time you don’t need to.

As we have seen VBA will automatically delete the object as soon as we go out of scope. So in most cases setting the object to Nothing is not doing anything.

The only time you would set a variable to Nothing is if you needed to empty memory straight away and couldn’t wait for the variable to go out of scope. An example would be emptying a Collection.

Imagine the following project. You open a workbook and for each worksheet you read all the customer data to a collection and process it in some way. In this scenario, you would set the Collection to Nothing every time you finish with a worksheet’s data.

' https://excelmacromastery.com/
Sub SetToNothing()
 
    ' Create collection
    Dim coll As New Collection
 
    Dim sh As Worksheet
    ' Go through all the worksheets
    For Each sh In ThisWorkbook.Worksheets
   
        ' Add items to collection
        
        ' Do something with the collection data
        
        ' Empty collection
        Set coll = Nothing
 
    Next sh
 
End Sub

Memory Summary

To sum up what we have learned in this section:

  1. A new object is created in memory when we use the New keyword.
  2. The object variable contains only the memory address of the object.
  3. Using Set changes the address in the object variable.
  4. If an object is no longer referenced then VBA will automatically delete it.
  5. Setting an object to Nothing is not necessary in most cases.

Why Set Is Useful

Let’s look at two examples that show how useful Set can be.

First, we create a very simple class module called clsCustomer and add the following code

Public Firstname As String
Public Surname As String

Set Example 1

In our first scenario, we are reading from a list of customers from a worksheet. The number of customers can vary between 10 and 1000.

Obviously, declaring 1000 objects isn’t an option. Not only is it a lot of wasteful code, it also means we can only deal with maximum 1000 customers.

' Don't do this!!!
Dim oCustomer1 As New clsCustomer
Dim oCustomer2 As New clsCustomer
' .
' .
' .
Dim oCustomer1000 As New clsCustomer

 
What we do first is to get the count of rows with data. Then we create a customer object for each row and fill it with data. We then add this customer object to the collection.

' https://excelmacromastery.com/
Sub ReadCustomerData()

    ' We will always have one collection
    Dim coll As New Collection
    
    ' The number of customers can vary each time we read a sheet
    Dim lLastRow As Long
    lLastRow = Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp).Row
    
    Dim oCustomer As clsCustomer
    Dim i As Long
    ' Read through the list of customers
    For i = 1 To lLastRow
    
        ' Create a new clsCustomer for each row
        Set oCustomer = New clsCustomer
        
        ' Add data
        oCustomer.Firstname = Sheet1.Range("A" & i)
        oCustomer.Surname = Sheet1.Range("B" & i)
        
        ' Add the clsCustomer object to the collection
        coll.Add oCustomer
        
    Next i

End Sub

 
Each time we use Set we are assigning oCustomer to “point” to the newest object. We then add the customer to the Collection. What happens here is that VBA creates a copy of the object variable and places it in the collection.

Set Example 2

Let’s look at a second example where using Set is useful. Imagine we have a fixed number of customers but only want to read the ones whose name starts with the letter B. We only create a customer object when we find a valid one.

' https://excelmacromastery.com/
Sub ReadCustomerB()

    ' We will always have one collection
    Dim coll As New Collection
   
    Dim oCustomer As clsCustomer, sFirstname As String
    Dim i As Long
    ' Read through the list of customers
    For i = 1 To 100
    
        sFirstname = Sheet1.Range("A" & i)
        
        ' Only create customer if name begins with B
        If Left(sFirstname, 1) = "B" Then
            ' Create a new clsCustomer
            Set oCustomer = New clsCustomer
            
            ' Add data
            oCustomer.Firstname = sFirstname
            oCustomer.Surname = Sheet1.Range("B" & i)
            
            ' Add to collection
            coll.Add oCustomer
        End If
        
    Next i

End Sub

 
It doesn’t matter how many customer names start with B this code will create exactly one object for each one.

 
This concludes my post on VBA Objects. I hope you found it beneficial.In my next post I’ll be looking at how you can create your own objects in VBA using the Class Module.

If you have any questions or queries please feel free to add a comment or email me at Paul@ExcelMacroMastery.com.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Содержание

  1. Общие сведения об объектах, методах, свойствах и событиях
  2. Объекты и коллекции
  3. Возврат объектов
  4. Методы
  5. Свойства
  6. События
  7. См. также
  8. Поддержка и обратная связь
  9. Understanding objects, methods, properties, and events
  10. Objects and collections
  11. Returning objects
  12. Methods
  13. Properties
  14. Events
  15. See also
  16. Support and feedback
  17. VBA Objects Properties and Methods in Excel
  18. VBA Reference
  19. 120+ Project Management Templates
  20. What are Objects?
  21. What are Properties?
  22. What are Methods?
  23. VBA Objects Properties and Methods in Excel – Object Browser?
  24. Excel VBA
  25. Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods

Общие сведения об объектах, методах, свойствах и событиях

Объекты и коллекции

Объект представляет элемент приложения, такой как лист, ячейка, диаграмма, форма или отчет. В коде Visual Basic необходимо идентифицировать объект, прежде чем можно будет применить один из методов объекта или изменить значение одного из его свойств.

Коллекция — это объект, который содержит несколько других объектов обычно, но не всегда, одного типа. Например, в Microsoft Excel объект Workbooks содержит все открытые объекты Workbook. В Visual Basic коллекция Forms содержит все объекты Form в приложении.

Элементы в коллекции могут идентифицироваться по номеру или по имени. Например, в указанной ниже процедуре первый открытый объект Workbook идентифицируется по номеру.

В приведенной ниже процедуре используется имя, указанное в виде строки, для идентификации объекта Form.

Можно также обрабатывать всю коллекцию объектов, если объекты совместно используют общие методы. Например, следующая процедура закрывает все открытые формы.

Возврат объектов

Каждое приложение имеет способ возврата содержащихся в нем объектов. Однако они отличаются, поэтому необходимо ознакомиться со справочным разделом по объектам или коллекциям, используемым в приложении, чтобы узнать, как возвратить объект.

Методы

Метод — это действие, которое может выполняться объектом. Например, Add — это метод объекта ComboBox, так как им добавляется новая запись в поле со списком.

В следующей процедуре метод Add используется для добавления нового элемента в ComboBox.

Свойства

Свойство — это атрибут объекта, которой определяется одно из характеристик объекта, такая как размер, цвет, местоположение экрана или характер поведения объекта, например включен ли он и является ли видимым. Чтобы изменить характеристики объекта, изменяют значения его свойств.

Чтобы установить значение свойства, введите после ссылки на объект точку, имя свойства, знак равенства (=) и новое значение свойства. Например, указанная ниже процедура изменяет заголовок формы Visual Basic путем установки свойства Caption.

Некоторые свойства невозможно установить. В справочном разделе по каждому свойству указывается, можно ли установить это свойство (чтение-запись), только прочитать свойство (только чтение) или только записать свойство (только запись).

Сведения об объекте можно получить путем возврата значения одного из его свойств. В приведенной ниже процедуре используется окно сообщения для демонстрации заголовка, отображаемого в верхней части активной формы.

События

Событие — это действие, распознаваемое объектом, например щелчок мыши или нажатие клавиши, для которого можно написать код реагирования. События могут возникать в результате действий пользователя или кода программы либо вызываться системой.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Understanding objects, methods, properties, and events

Objects and collections

An object represents an element of an application, such as a worksheet, a cell, a chart, a form, or a report. In Visual Basic code, you must identify an object before you can apply one of the object’s methods or change the value of one of its properties.

A collection is an object that contains several other objects, usually, but not always, of the same type. In Microsoft Excel, for example, the Workbooks object contains all the open Workbook objects. In Visual Basic, the Forms collection contains all the Form objects in an application.

Items in a collection can be identified by number or by name. For example, the following procedure identifies the first open Workbook object.

The following procedure uses a name specified as a string to identify a Form object.

You can also manipulate an entire collection of objects if the objects share common methods. For example, the following procedure closes all open forms.

Returning objects

Every application has a way to return the objects it contains. However, they are not all the same, so you must refer to the Help topic for the object or collection that you are using in the application to see how to return the object.

Methods

A method is an action that an object can perform. For example, Add is a method of the ComboBox object, because it adds a new entry to a combo box.

The following procedure uses the Add method to add a new item to a ComboBox.

Properties

A property is an attribute of an object that defines one of the object’s characteristics, such as size, color, or screen location, or an aspect of its behavior, such as whether it is enabled or visible. To change the characteristics of an object, you change the values of its properties.

To set the value of a property, follow the reference to an object with a period, the property name, an equal sign (=), and the new property value. For example, the following procedure changes the caption of a Visual Basic form by setting the Caption property.

You can’t set some properties. The Help topic for each property indicates whether you can set that property (read-write), only read the property (read-only), or only write the property (write-only).

You can retrieve information about an object by returning the value of one of its properties. The following procedure uses a message box to display the title that appears at the top of the currently active form.

Events

An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. Events can occur as a result of a user action or program code, or they can be triggered by the system.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Objects Properties and Methods in Excel

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word Templates

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates

Understanding VBA Objects Properties and Methods in Excel is important, most of the programming languages today are Object Based Or Object Oriented Programming Languages. Although Excel VBA is not a truly object oriented programming language, it does deal with objects.

In this Section:

What are Objects?

Most of the programming languages today are Object Based Or Object Oriented Programming Languages. Although Excel VBA is not a truly object oriented programming language, it does deal with objects.
VBA object is something like a thing that has certain functions, properties, and can contain data or child objects.

In real world everything is an object. For example, House is an Object, Windows and Doors,etc… are child objects of the House. And House is having some characteristics or properties such as Color, Height, Number of Floors,etc. and it also have some Events, such as Door Open, Door Close, etc….

Similarly, An Excel Worksheet is an object, and a Range or Cells in a worksheet are child objects of worksheet, Worksheet contains several Properties, Methods and Events.
You can go to the code window to view the VBA objects, the upper left drop-down list of the code window contains the list of objects and the right side drop-down list contains the associated objects.

What are Properties?

Properties are the characteristics of an Objects which can be measured and quantified, in the above example House is having properties like Width, Height, Color, etc…
Similarly, Excel Objects are having several properties which can be measured and quantified.

For example, a Range Objects is having Properties like Value,Font.ColorIndex, Interior.ColorIndex,etc…

What are Methods?

Methods are the actions that can be performed by an an Objects or on an Object. In the above Hose example, paintaing is a Method, building a new room is a method.
Similarly, if you want to select a range, you need Select method. If you want to copy a range from one worksheet to another worksheet you need Copy method to do it.

The following example Copies the data from Range A1 to B5.

VBA Objects Properties and Methods in Excel – Object Browser?

Object browser is a very helpful tool available in VBA, which helps you to veiw all available Objects in the Excel VBA. Click on the objects browser in the code window to view all the available Excel VBA objects and its associated Properties and Methods.

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Источник

Excel VBA

Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods

User Rating: 4 / 5

Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods

Contents:

An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object, a Method is an action performed by an object. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. An object is a thing which contains data and has properties and methods. To manipulate an Object you will Set its Properties and Call its Methods.

Visual Basic is not truly an Object-Orientated Programming (OOP) Language

Visual Basic (Visual Basic 6) is not truly an Object-Orientated Programming (OOP) Language whereas its successor Visual Basic.NET (part of the .NET platform) is a full-fledged Object Oriented programming language meeting the criteria of encapsulation, inheritance and polymorphism, where everything in Visual Basic.NET can be treated as an object. Visual Basic has many (but not all) elements of an Object-Orientated Programming (OOP) language. VBA deals with objects but is not truly an Object-Orientated Programming language.

VBA Objects

An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object (like name, color, size) or define an object’s behaviour (viz. if visible or enabled). An object’s data or information can be accessed with properties (viz. Value property, Name property). A Method is an action performed by an object. Calling a Method will execute a vba code which will cause the object to perform an action. You can associate objects with nouns, properties with adjectives and methods with verbs. An object could be a house, car, table or pen. Properties of a car include its color or size, which describe it. A car can perform actions of moving, accelerating or turning which are its methods. Examples of objects in Excel are workbook, worksheet, range, command button, font, etc. A Range object has «Value» as one of its properties and «Select» as one of its methods. Similarly a worksheet has, among others, a «Name» property, a «Delete» method, and a «Copy» method having arguments which contain information in respect of the worksheet to be copied.

Objects also have event procedures attached to them. Events are actions performed, or occurrences, which trigger a VBA code or macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. Excel provided built-in event procedure — an Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls. Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». In the Worksheet Change event procedure, the Worksheet object is associated with the Change event, which means that with the worksheet change event, a sub-procedure containing customized code runs automatically when you change the contents of a worksheet cell. Custom Events — you can also define your own events in custom classes (class modules), and create event procedures that run when those events occur.

A Collection Object in vba refers to a group of related items, as a single object. Many objects are present both in single form as well as in multiples. For example: (i) Workbook & Workbooks — all open Workbook objects in Excel are referred to as the Workbooks collection; (ii) Worksheet & Worksheets — A Worksheets Collection object refers to all Worksheets contained in a workbook. All elements (items) of a collection share the same properties and methods, though they do not need to be of the same data type. You can either create your own collection using the vba Collection class or use the Excel VBA built-in collections such as Worksheets (the Worksheets Collection Object includes all Worksheets in a workbook). With a Collection Object you can work with all objects (which are its elements) as a group as against working with a single object. The basic ways of working with elements of a collection include: adding an element using the Add method, removing an element using the Remove method, determining the number of elements contained in a collection using the Count property, accessing a specific element using the Item property, enumerate each element of a collection using the For Each. Next Statement, and so on.

The Excel Object Model

All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. When you use vba in an Office Application, say PowerPoint, a reference to the PowerPoint Object Library is set by default. When you Automate to work with PowerPoint objects from another application, say Excel, you can add a reference to the PowerPoint object library in Excel (your host application) by clicking Tools-References in VBE, which will enable using PowerPoint’s predefined constants — the PowerPoint objects, properties, and methods will appear in the Object Browser and the syntax will be checked at compile time.

The Object Model of the Application (Excel) refers to and contains its programming objects which are related to each other in a hierarchy. The entire Excel application is represented by the Application Object which is at the top of the Excel object hierarchy and moving down you can access the objects from Application to Workbook to Worksheet to Range (Cells) and further on, by connecting the objects with a period (dot). Excel objects are accessed through ‘parent’ objects — Worksheet is the parent of the Range Object, and the Workbook is the parent of the Worksheet object, and the Application object is the parent of the Workbook object.

Example — Start at the top of the hierarchy with the Application object, then move down to the workbook, worksheet, range and font objects, as follows:

The Excel Object Model hierarchy — the most used objects:

The Application Object refers to the host application of Excel, and the entire Excel application is represented by it. The Workbook Object, appears next below the Application Object in Excel object hierarchy, and represents a single workbook within the Excel application. A workbook is also referred to as an Excel file. The Workbooks Collection Object includes all currently open Workbooks in Excel. The Worksheet Object, appears next below the Workbook Object in Excel object hierarchy, and represents a single worksheet within the workbook. The Worksheets Collection Object includes all Worksheets in a workbook. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells (when the Range is a union of multiple blocks of cells it is referred as a non-contiguous range of cells). The Range object is usually used maximum within the Excel application.

The Application object is the Default Object, Excel assumes it even when it is not specified. The Application qualifier is mostly not required to be used in vba code, because the default application is Excel itself, unless you want to refer to other outside applications (like Microsoft Word or Access) in your code or you want to refer to Excel from another application like Microsoft Word. In your VBA code, both the expressions Application.ActiveWorkbook.Name and ActiveWorkbook.Name will have the same effect of returning the Active Workbook’s name. However, there are some instances when the Application qualifier is required to be used, viz. generally when using properties & methods which relate to the Excel window’s appearance, or which relate to how the excel application behaves as a whole.

The Active Object

If no Workbook or Worksheet is specified, Excel refers to the current Active Workbook or Worksheet by default. In your vba code you can also refer the current Active Workbook or Sheet as ActiveWorkbook or ActiveSheet. Both the expressions Worksheets(1).Name and ActiveWorkbook.Worksheets(1).Name will return the name of the first worksheet in the Active Workbook which also becomes the default object in this case. Similarly, both the expressions Range(«A1»).Value = 56 and ActiveSheet.Range(«A1»).Value = 56 will enter the value 56 in cell A1 of the Active Worksheet in the Active Workbook. This is a general rule that omitting reference to a Workbook or Worksheet refers to the current Active Workbook or Worksheet by default, but this rule is subject to below conditions.

Note : (i) omitting reference to a Worksheet when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, . ) will reference the specific sheet in whose module your code is entered and NOT the Active Sheet; and (ii) omitting reference to a Workbook when your vba code is entered in the Workbook module (ThisWorkbook) will reference the workbook in which your code is entered and NOT the Active Workbook. This means: (i) omitting reference to a Worksheet will default to ActiveSheet when your vba code is entered in Standard Code Modules (Module1, Module2, …) or the Workbook module (ThisWorkbook) and NOT when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, . ) or UserForms or any Class modules you create; and (ii) omitting reference to a Workbook will default to ActiveWorkbook when your vba code is entered in Standard Code Modules (Module1, Module2, …) or in the Sheet Modules (viz. Sheet1, Sheet2, . ) and NOT when your vba code is entered in the Workbook module (ThisWorkbook).

Access an Object / Access a Single Object from its Collection

Access a Workbook Object

Workbook Object and Workbooks Collection: All open Workbook objects in Excel are referred to as the Workbooks collection. You can access a single Workbook from the Workbooks Collection by using the workbook index. This index is either the workbook name or an index number, and is used as Workbooks(index). To activate a workbook named «VbaProject», use Workbooks(«VbaProject»).Activate. To activate the first workbook, use Workbooks(1).Activate. The index number starts at 1, which indicates the first workbook which is created or opened, and the last workbook number will be returned by Workbooks.Count (which counts the number of open workbooks). The activate the second workbook use Workbooks(2).Activate, to activate the last workbook use Workbooks(Workbooks.Count).Activate.

Access a Worksheet Object

Worksheet Object and Worksheets Collection: A Worksheets Collection object refers to all Worksheets contained in a workbook. Similar to a Workbook object, you can access a single Worksheet from the Worksheets Collection by using the worksheet index. The index can be the worksheet name or an index number, and is used as Worksheets(index). To activate a worksheet named «Sheet1», use Worksheets(«Sheet1»).Activate. To activate the first worksheet, use Worksheets(1).Activate. The index number starts at 1, which indicates the first worksheet, and the last worksheet number will be returned by Worksheets.Count (which counts the number of worksheets in a workbook). The activate the second worksheet use Worksheets(2).Activate, to activate the last worksheet use Worksheets(Worksheets.Count).Activate.

Access a Sheet Object

Sheet Object and Sheets Collection: A Sheets Collection object refers to all sheets contained in a workbook, which includes chart sheets and worksheets. You can access a single Sheet from the Sheets Collection by using the sheet index viz. Sheets(index), similar to accessing a Worksheet. The Sheet index can be the sheet name viz. Sheets(«Sheet1»).Activate, or index number viz. Sheets(1).Activate or Sheets(Sheets.Count).Activate.

Access a Range Object

A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. You can refer to a range by using the following expressions.

Referencing a single cell:

Enter the value 10 in the cell A1 of the worksheet named «Sheet1»:

Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:

ActiveSheet.Cells(2, 3).Value = 10

Referencing a range of cells:

Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:

ActiveSheet.Range(«A1», «B3»).Value = 10

ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10

Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:

Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:

Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:

Select all the cells of the active worksheet:

Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:

ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»

Referencing Row(s) or Column(s):

Select all the Rows of active worksheet:

Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:

Select all the Columns of the active worksheet:

Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:

Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:

Relative Referencing:

Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:

Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:

Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:

Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:

Properties and Methods of Objects

As explained above, to manipulate an Object you can Set its Properties and Call its Methods.

To access the property of an object, connect the Object Name to the Property by inserting a period (full stop or dot) between them viz. Worksheets(1).Name, returns the name of the first worksheet. Some objects have default properties viz. a Range object’s default property is Value and you can omit to mention Value. In this case using Range(«A1»).Value or only Range(«A1») is the same and will return the value or content of the Cell A1, and the expressions can be used alternatively. Properties can be: (i) a Read-only property, which means you can read or access but cannot change it; or (ii) a Read-write property, in which case your VBA code can both read or change value.

To access the method of an object, connect the Object Name to the Method by inserting a period (full stop or dot) between them viz. Worksheets(1).Activate, activates the first worksheet by calling the Activate method. A Method may or may not have argument(s). An argument is a value supplied to a method to enable it to perform an action. To use the Calculate & Activate Method on a Worksheet object, you need not supply an argument viz. Worksheets(«Sheet1»).Calculate or Worksheets(«Sheet1»).Activate. To use the Add Method on a Worksheets Collection Object, you need to supply multiple arguments.

An Object’s Method is a procedure that acts on it. A Method can have Arguments which are required to be specified and/or it can have Optional Arguments which you can omit to specify. Arguments which are displayed in square brackets in the method’s syntax, are optional while others are required. The arguments can be supplied in the order of the position in which they are defined in the method syntax, each argument value being separated with a comma even for optional arguments which may not be specified. Alternatively the arguments can be supplied by the argument name (referred as named arguments) in which case the position in which they are specified becomes irrelevant. Each Named argument will also be separated with a comma, but not for optional arguments which are not specified. While specifying named arguments, you specify the argument name followed by a colon and an equal sign (:=) which is followed by the argument value, viz. ArgumentName:= «ArgumentValue» . Using named arguments will facilitate keeping a track of the arguments which have been specified and those which have been omitted.

Examples of using an Object’s Method:

The Activate Method applied to a Worksheet Object, activates the specified worksheet and makes it current. This method has no argument(s).

The Add Method applied to a Worksheets Collection Object, creates a new worksheet. It has multiple arguments, all of which are Optional. Syntax: Worksheets.Add(Before, After, Count, Type).

Using the Add Method without specifying any argument — adds a new worksheet before the Active Worksheet because both the Before & After arguments are omitted (note that the default value of Count argument is 1):

Using the Add Method specifying one named argument of After — adds a new worksheet after the Worksheet named «Sheet2» (note that the default value of Count argument is 1):

Using the Add Method specifying two named arguments of After & Count — adds 3 new worksheets after the Worksheet named «Sheet2»:

Worksheets.Add After:=Worksheets(«Sheet2»), Count:=3

Using the Add Method specifying two positional arguments of After & Count — adds 2 new worksheets after the Worksheet named «Sheet2»:

Worksheets.Add , Worksheets(«Sheet2»), 2

Using the Add Method specifying two positional arguments of Before & Count — adds 2 new worksheets before the Worksheet named «Sheet2»:

Worksheets.Add Worksheets(«Sheet2»), , 2

Using the Add Method specifying one named argument of Before — adds a new worksheet before the Worksheet named «Sheet2», and using the Name property, names the new worksheet «NewSheet»:

Working with Objects in Excel VBA

Excel VBA IntelliSense

While writing vba code, when you type an Object followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense). Ensure that the Excel VBA IntelliSense is turned on: in VBE, Tools>Options>Editor, ‘Auto List Members’ should be selected/checked. For instance, the IntelliSense will pop up after you type range followed by a period viz. range.[Intellisense for a Range object Pops Up]. Refer Image 2 — properties of the Range object are indicated by the fingers and methods of the Range object are indicated by the green boxes/bricks. You can either type or else select from this pop-up list, the method or property you want to connect with the object.

Using With…End With Statement to refer to Objects

As explained earlier, to access an Object and its properties & methods, you have to use the object name. In your vba code you will often need to refer to an object multiple times, and each time you will have to use its name. Instead of using the object name every time, you can execute multiple code lines which repeatedly refer to an object, by using the With…End With Statement. You start the block with the first line as:- type the With keyword followed by the Object Name. Insert one or more code lines after the first line:- access the object’s members (its properties, methods, etc) by typing a period (dot) followed by the property or method name, and you need not specify the object name each time. Terminate the block with the end line:- «End With». Refer to the below example, which shows how to make your vba code more readible using a With Block, and with Nesting ie. Block within a Block:

‘use the With . End With statement to refer to a Range object
With Worksheets(«Sheet1»).Range(«A1»)

‘use the Value property of the Range object, to set the value for the range:
.Value = 11
‘use the Name property, of the Range object, to set the range name:
.Name = «Score»

‘use the Font Property of the Range object that returns a Font object, and then use the With . End With statement to refer to the Font object
With .Font

‘note that because you are using the With . End With statement to refer to the Font object within the Range object, you will not refer to both the range or font objects below:
‘use the Name property of the Font object to set the font name:
.Name = «Arial»
‘use the Bold property of the Font object to set the font to bold:
.Bold = True
‘use the Color property of the Font object to set the font color:

‘use the Borders property of the Range object to return all four borders (Borders collection object), and then use the LineStyle property of the Borders object to add a double border:
.Borders.LineStyle = xlDouble

‘the Clear Method of the Range object, clears the range (clears the contents, formulas and formatting):

Using Variables in VBA

A variable is a named storage location used to store temporary values or information for use in execution of the code. In your vba program, a variable stores data and its content is used or changed later while executing the code. By declaring a variable for use in your code, you tell the Visual Basic compiler the variable’s data type (type of value it represents viz. integer, decimal, text, boolean, etc.) and other information such as its scope/level (what code can access it — variables can be Procedure Level, Module Level or can have a Public scope). Variables must be explicitly declared using the Dim, Private, Public, ReDim, or Static statements. When you declare variables by using a Dim statement (Dim is short for dimension): for declaring a variable to hold an Integer value, use «Dim rowNumber As Integer»; for declaring a variable to hold text values, use «Dim strEmployeeName As String»; and so on.

Keywords in VBA

Keywords are reserved words that VBA uses as part of its programming language. Keywords are words or commands that are recognized by VBA and can be used in vba code only as part of the vba language (like in a statement, function name, or operator) and not otherwise (like sub-procedure or variable names). Examples of keywords are: Sub, End, Dim, If, Next, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, and so on. To get help on a particular keyword, insert your mouse cursor within the keyword (in your vba code in VBE ) and press F1. Note that Keywords get capitalized in the vba code indicating that they have been written correctly viz. typing next will automatically appear as Next.

Assign an Object to a Variable, using the Set Keyword

In VBA, you use the Set keyword to assign an object reference. To assign an object to a variable in your vba code, you need to use the Set keyword as shown below. Note that using the Dim, Private or Public statements you only declare a variable as to its data type (type of value it represents viz. integer, text, etc.) and other information such as its scope/level (what code can access it). The actual object is assigned or referred to it only by using the Set statement. It is shorter to use an object variable & also more convenient because its data type will be known by VBA so that when you type the variable followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense).

Example : With the following code, we declare a variable (myRange) of Range data type, and then assign the Range object to this variable using the Set keyword, so that every time you want to refer to the specific Range, you can do so by using the variable. The following will enter the value 10 in cells A1 to C3 in the worksheet named «Sheet1».

Источник

Skip to content

VBA Objects Properties and Methods in Excel

Understanding VBA Objects Properties and Methods in Excel is important, most of the programming languages today are Object Based Or Object Oriented Programming Languages. Although Excel VBA is not a truly object oriented programming language, it does deal with objects.

In this Section:

  • What are Objects?
  • What are Properties?
  • What are Methods?
  • Object Browser?

What are Objects?

Most of the programming languages today are Object Based Or Object Oriented Programming Languages. Although Excel VBA is not a truly object oriented programming language, it does deal with objects.
VBA object is something like a thing that has certain functions, properties, and can contain data or child objects.

In real world everything is an object. For example, House is an Object, Windows and Doors,etc… are child objects of the House. And House is having some characteristics or properties such as Color, Height, Number of Floors,etc.., and it also have some Events, such as Door Open, Door Close, etc….

Similarly, An Excel Worksheet is an object, and a Range or Cells in a worksheet are child objects of worksheet, Worksheet contains several Properties, Methods and Events.
You can go to the code window to view the VBA objects, the upper left drop-down list of the code window contains the list of objects and the right side drop-down list contains the associated objects.

Objects-Example-1

What are Properties?

Properties are the characteristics of an Objects which can be measured and quantified, in the above example House is having properties like Width, Height, Color, etc…
Similarly, Excel Objects are having several properties which can be measured and quantified.

For example, a Range Objects is having Properties like Value,Font.ColorIndex, Interior.ColorIndex,etc…

Sub sbExampleRangeProperties()
Range("A1").Value = 25
Range("A1").Interior.ColorIndex = 5
End Sub

Objects-Example-2

What are Methods?

Methods are the actions that can be performed by an an Objects or on an Object. In the above Hose example, paintaing is a Method, building a new room is a method.
Similarly, if you want to select a range, you need Select method. If you want to copy a range from one worksheet to another worksheet you need Copy method to do it.

The following example Copies the data from Range A1 to B5.

Sub sbExampleRangeMethods()
    Range("A1").Select
    Selection.Copy
    Range("B5").Select
    ActiveSheet.Paste
End Sub

Objects-Example-3

VBA Objects Properties and Methods in Excel – Object Browser?

Object browser is a very helpful tool available in VBA, which helps you to veiw all available Objects in the Excel VBA. Click on the objects browser in the code window to view all the available Excel VBA objects and its associated Properties and Methods.
Objects-Example-4

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • What are Objects?
    • What are Properties?
    • What are Methods?
    • VBA Objects Properties and Methods in Excel – Object Browser?

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

9 Comments

  1. NAGESWARA RAO
    January 6, 2015 at 2:37 PM — Reply
  2. Yogarajah
    October 6, 2015 at 8:44 AM — Reply

    Very simple explanation of objects,Properties and Methods in VBA. Congratulation.

  3. Nafis
    April 18, 2016 at 10:09 AM — Reply

    Thanks, deep explanation in very simple way. it clears the concept very easily.

    Thanks again.

  4. hemant
    June 11, 2016 at 2:38 PM — Reply

    Good ,simple explaination

  5. Ashok
    October 22, 2016 at 10:01 AM — Reply

    It is very easy and simple to understand the subject

  6. Vignesh
    May 8, 2017 at 4:41 PM — Reply
  7. Sivaji
    May 19, 2017 at 11:47 PM — Reply

    Thank u sooo much dear gud explanation

  8. Remmy
    August 8, 2017 at 12:39 PM — Reply

    I bought a massive VBA book on Amazon and having read it over and over again, it still couldn’t understand properly what these things are. You, however, nailed it in a few word. Thank you.

  9. PNRao
    August 8, 2017 at 2:18 PM — Reply

    We are glad to hear that you this useful.
    Thank you very mach!

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods

————————————————————————————

Contents:

VBA Objects

The Excel Object Model

Active Object

Access an Object / Access a Single Object from its Collection

Properties and Methods of Objects

Working with Objects in Excel VBA

————————————————————————————

An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object, a Method is an action performed by an object. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. An object is a thing which contains data and has properties and methods. To manipulate an Object you will Set its Properties and Call its Methods.

For more articles related to Excel VBA objects: Excel VBA Application Object, the Default Object in Excel; Excel VBA Workbook Object, working with Workbooks in Excel; Microsoft Excel VBA — Worksheets; Excel VBA Range Object, Referencing Cells and Ranges; Excel VBA Custom Classes and Objects.

Visual Basic is not truly an Object-Orientated Programming (OOP) Language

Visual Basic (Visual Basic 6) is not truly an Object-Orientated Programming (OOP) Language whereas its successor Visual Basic.NET (part of the .NET platform) is a full-fledged Object Oriented programming language meeting the criteria of encapsulation, inheritance and polymorphism, where everything in Visual Basic.NET can be treated as an object. Visual Basic has many (but not all) elements of an Object-Orientated Programming (OOP) language. VBA deals with objects but is not truly an Object-Orientated Programming language.

VBA Objects

An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object (like name, color, size) or define an object’s behaviour (viz. if visible or enabled). An object’s data or information can be accessed with properties (viz. Value property, Name property). A Method is an action performed by an object. Calling a Method will execute a vba code which will cause the object to perform an action. You can associate objects with nouns, properties with adjectives and methods with verbs. An object could be a house, car, table or pen. Properties of a car include its color or size, which describe it. A car can perform actions of moving, accelerating or turning which are its methods. Examples of objects in Excel are workbook, worksheet, range, command button, font, etc. A Range object has «Value» as one of its properties and «Select» as one of its methods. Similarly a worksheet has, among others, a «Name» property, a «Delete» method, and a «Copy» method having arguments which contain information in respect of the worksheet to be copied.

Objects also have event procedures attached to them. Events are actions performed, or occurrences, which trigger a VBA code or macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. Excel provided built-in event procedure — an Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls.  Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». In the Worksheet Change event procedure, the Worksheet object is associated with the Change event, which means that with the worksheet change event, a sub-procedure containing customized code runs automatically when you change the contents of a worksheet cell. Custom Events — you can also define your own events in custom classes (class modules), and create event procedures that run when those events occur.

A Collection Object in vba refers to a group of related items, as a single object. Many objects are present both in single form as well as in multiples. For example: (i) Workbook & Workbooks — all open Workbook objects in Excel are referred to as the Workbooks collection; (ii) Worksheet & Worksheets — A Worksheets Collection object refers to all Worksheets contained in a workbook. All elements (items) of a collection share the same properties and methods, though they do not need to be of the same data type. You can either create your own collection using the vba Collection class or use the Excel VBA built-in collections such as Worksheets (the Worksheets Collection Object includes all Worksheets in a workbook). With a Collection Object you can work with all objects (which are its elements) as a group as against working with a single object. The basic ways of working with elements of a collection include: adding an element using the Add method, removing an element using the Remove method, determining the number of elements contained in a collection using the Count property, accessing a specific element using the Item property, enumerate each element of a collection using the For Each…Next Statement, and so on.

The Excel Object Model

All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. When you use vba in an Office Application, say PowerPoint, a reference to the PowerPoint Object Library is set by default. When you Automate to work with PowerPoint objects from another application, say Excel, you can add a reference to the PowerPoint object library in Excel (your host application) by clicking Tools-References in VBE, which will enable using PowerPoint’s predefined constants — the PowerPoint objects, properties, and methods will appear in the Object Browser and the syntax will be checked at compile time.

All objects, and their associated Properties and Methods, available in Excel VBA can be viewed in the Object Browser in the VBE code window — in VBE click on View>Object Browser or press F2. On the top-left of the window is the Project/Library box, which by default mentions <All Libraries>, wherein you can choose Excel from the list to view all Excel objects. On the left pane of the window the available Classes (Objects) are listed, and on the right pane are displayed all Members (ie. properties, methods, events & constants) associated with the selected object in the Classes list. Global members (ie. properties, methods, events & constants) are those in respect of which the object name can be omitted. In the Excel Object Library, those properties and methods whose use does not require specifying the Application object qualifier are considered «global». Refer Image 1 to view the Object Browser.

The Object Model of the Application (Excel) refers to and contains its programming objects which are related to each other in a hierarchy. The entire Excel application is represented by the Application Object which is at the top of the Excel object hierarchy and moving down you can access the objects from Application to Workbook to Worksheet to Range (Cells) and further on, by connecting the objects with a period (dot). Excel objects are accessed through ‘parent’ objects — Worksheet is the parent of the Range Object, and the Workbook is the parent of the Worksheet object, and the Application object is the parent of the Workbook object.

Example — Start at the top of the hierarchy with the Application object, then move down to the workbook, worksheet, range and font objects, as follows:

Application.ActiveWorkbook.Worksheets(1).Range(«A1»).Font

The Excel Object Model hierarchy — the most used objects:

The Application Object refers to the host application of Excel, and the entire Excel application is represented by it. The Workbook Object, appears next below the Application Object in Excel object hierarchy, and represents a single workbook within the Excel application. A workbook is also referred to as an Excel file. The Workbooks Collection Object includes all currently open Workbooks in Excel. The Worksheet Object, appears next below the Workbook Object in Excel object hierarchy, and represents a single worksheet within the workbook. The Worksheets Collection Object includes all Worksheets in a workbook. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells (when the Range is a union of multiple blocks of cells it is referred as a non-contiguous range of cells). The Range object is usually used maximum within the Excel application.

The Application object is the Default Object, Excel assumes it even when it is not specified. The Application qualifier is mostly not required to be used in vba code, because the default application is Excel itself, unless you want to refer to other outside applications (like Microsoft Word or Access) in your code or you want to refer to Excel from another application like Microsoft Word. In your VBA code, both the expressions Application.ActiveWorkbook.Name and ActiveWorkbook.Name will have the same effect of returning the Active Workbook’s name. However, there are some instances when the Application qualifier is required to be used, viz. generally when using properties & methods which relate to the Excel window’s appearance, or which relate to how the excel application behaves as a whole.

The Active Object

If no Workbook or Worksheet is specified, Excel refers to the current Active Workbook or Worksheet by default. In your vba code you can also refer the current Active Workbook or Sheet as ActiveWorkbook or ActiveSheet. Both the expressions Worksheets(1).Name and ActiveWorkbook.Worksheets(1).Name will return the name of the first worksheet in the Active Workbook which also becomes the default object in this case. Similarly, both the expressions Range(«A1»).Value = 56 and ActiveSheet.Range(«A1»).Value = 56 will enter the value 56 in cell A1 of the Active Worksheet in the Active Workbook. This is a general rule that omitting reference to a Workbook or Worksheet refers to the current Active Workbook or Worksheet by default, but this rule is subject to below conditions.

Note: (i) omitting reference to a Worksheet when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, …) will reference the specific sheet in whose module your code is entered and NOT the Active Sheet; and (ii) omitting reference to a Workbook when your vba code is entered in the Workbook module (ThisWorkbook) will reference the workbook in which your code is entered and NOT the Active Workbook. This means: (i) omitting reference to a Worksheet will default to ActiveSheet when your vba code is entered in Standard Code Modules (Module1, Module2, …) or the Workbook module (ThisWorkbook) and NOT when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, …) or UserForms or any Class modules you create; and (ii) omitting reference to a Workbook will default to ActiveWorkbook when your vba code is entered in Standard Code Modules (Module1, Module2, …) or in the Sheet Modules (viz. Sheet1, Sheet2, …) and NOT when your vba code is entered in the Workbook module (ThisWorkbook).

Access an Object / Access a Single Object from its Collection

Access a Workbook Object

Workbook Object and Workbooks Collection: All open Workbook objects in Excel are referred to as the Workbooks collection. You can access a single Workbook from the Workbooks Collection by using the workbook index. This index is either the workbook name or an index number, and is used as Workbooks(index). To activate a workbook named «VbaProject», use Workbooks(«VbaProject»).Activate. To activate the first workbook, use Workbooks(1).Activate. The index number starts at 1, which indicates the first workbook which is created or opened, and the last workbook number will be returned by Workbooks.Count (which counts the number of open workbooks). The activate the second workbook use Workbooks(2).Activate, to activate the last workbook use Workbooks(Workbooks.Count).Activate.

Access a Worksheet Object

Worksheet Object and Worksheets Collection: A Worksheets Collection object refers to all Worksheets contained in a workbook. Similar to a Workbook object, you can access a single Worksheet from the Worksheets Collection by using the worksheet index. The index can be the worksheet name or an index number, and is used as Worksheets(index). To activate a worksheet named «Sheet1», use Worksheets(«Sheet1»).Activate. To activate the first worksheet, use Worksheets(1).Activate. The index number starts at 1, which indicates the first worksheet, and the last worksheet number will be returned by Worksheets.Count (which counts the number of worksheets in a workbook). The activate the second worksheet use Worksheets(2).Activate, to activate the last worksheet use Worksheets(Worksheets.Count).Activate.

Access a Sheet Object

Sheet Object and Sheets Collection: A Sheets Collection object refers to all sheets contained in a workbook, which includes chart sheets and worksheets. You can access a single Sheet from the Sheets Collection by using the sheet index viz. Sheets(index), similar to accessing a Worksheet. The Sheet index can be the sheet name viz. Sheets(«Sheet1»).Activate, or index number viz. Sheets(1).Activate or Sheets(Sheets.Count).Activate.

Access a Range Object

A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. You can refer to a range by using the following expressions.

Referencing a single cell:

Enter the value 10 in the cell A1 of the worksheet named «Sheet1»:

Worksheets(«Sheet1»).Range(«A1»).Value = 10

Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:

ActiveSheet.Cells(2, 3).Value = 10

Referencing a range of cells:

Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:

ActiveSheet.Range(«A1:B3»).Value = 10

ActiveSheet.Range(«A1», «B3»).Value = 10

ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10

Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Range(«A1,B3»).Value = 10

Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:

ActiveWorkbook.Worksheets(«Sheet3»).Range(«B2:D3,H7»).Interior.Color = vbRed

Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:

Range(«Score»).Value = 10

ActiveSheet.Range(«Score»).Value = 10

Select all the cells of the active worksheet:

ActiveSheet.Cells.Select

Cells.Select

Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:

ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»

ActiveSheet.Cells.Font.Size = 11

Cells.Font.Size = 11

Referencing Row(s) or Column(s):

Select all the Rows of active worksheet:

ActiveSheet.Rows.Select

Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Rows(2).Value = 10

Select all the Columns of the active worksheet:

ActiveSheet.Columns.Select

Columns.Select

Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:

ActiveSheet.Columns(3).Value = 10

Columns(«C»).Value = 10

Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Columns(«A:C»).Value = 10

Relative Referencing:

Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«A1») = 10

Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«B2») = 10

Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:

Range(«C5»).Offset(1, 2) = 10

Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:

Range(«C5:E8»).Offset(2, 3) = 10

Properties and Methods of Objects

As explained above, to manipulate an Object you can Set its Properties and Call its Methods.

To access the property of an object, connect the Object Name to the Property by inserting a period (full stop or dot) between them viz. Worksheets(1).Name, returns the name of the first worksheet. Some objects have default properties viz. a Range object’s default property is Value and you can omit to mention Value. In this case using Range(«A1»).Value or only  Range(«A1») is the same and will return the value or content of the Cell A1, and the expressions can be used alternatively. Properties can be: (i) a Read-only property, which means you can read or access but cannot change it; or (ii) a Read-write property, in which case your VBA code can both read or change value.

To access the method of an object, connect the Object Name to the Method by inserting a period (full stop or dot) between them viz. Worksheets(1).Activate, activates the first worksheet by calling the Activate method. A Method may or may not have argument(s). An argument is a value supplied to a method to enable it to perform an action. To use the Calculate & Activate Method on a Worksheet object, you need not supply an argument viz. Worksheets(«Sheet1»).Calculate or Worksheets(«Sheet1»).Activate. To use the Add Method on a Worksheets Collection Object, you need to supply multiple arguments.

An Object’s Method is a procedure that acts on it. A Method can have Arguments which are required to be specified and/or it can have Optional Arguments which you can omit to specify. Arguments which are displayed in square brackets in the method’s syntax, are optional while others are required. The arguments can be supplied in the order of the position in which they are defined in the method syntax, each argument value being separated with a comma even for optional arguments which may not be specified. Alternatively the arguments can be supplied by the argument name (referred as named arguments) in which case the position in which they are specified becomes irrelevant. Each Named argument will also be separated with a comma, but not for optional arguments which are not specified. While specifying named arguments, you specify the argument name followed by a colon and an equal sign (:=) which is followed by the argument value, viz. ArgumentName:= «ArgumentValue». Using named arguments will facilitate keeping a track of the arguments which have been specified and those which have been omitted.

Examples of using an Object’s Method:

The Activate Method applied to a Worksheet Object, activates the specified worksheet and makes it current. This method has no argument(s).

Worksheets(«Sheet1»).Activate

The Add Method applied to a Worksheets Collection Object, creates a new worksheet. It has multiple arguments, all of which are Optional. Syntax: Worksheets.Add(Before, After, Count, Type).

Using the Add Method without specifying any argument — adds a new worksheet before the Active Worksheet because both the Before & After arguments are omitted (note that the default value of Count argument is 1):

Worksheets.Add

Using the Add Method specifying one named argument of After — adds a new worksheet after the Worksheet named «Sheet2» (note that the default value of Count argument is 1):

Worksheets.Add After:=Worksheets(«Sheet2»)

Using the Add Method specifying two named arguments of After & Count — adds 3 new worksheets after the Worksheet named «Sheet2»:

Worksheets.Add After:=Worksheets(«Sheet2»), Count:=3

Using the Add Method specifying two positional arguments of After & Count — adds 2 new worksheets after the Worksheet named «Sheet2»:

Worksheets.Add , Worksheets(«Sheet2»), 2

Using the Add Method specifying two positional arguments of Before & Count — adds 2 new worksheets before the Worksheet named «Sheet2»:

Worksheets.Add Worksheets(«Sheet2»), , 2

Using the Add Method specifying one named argument of Before — adds a new worksheet before the Worksheet named «Sheet2», and using the Name property, names the new worksheet «NewSheet»:

Worksheets.Add(Before:=Worksheets(«Sheet2»)).Name = «NewSheet»

Working with Objects in Excel VBA

Excel VBA IntelliSense

While writing vba code, when you type an Object followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense). Ensure that the Excel VBA IntelliSense is turned on: in VBE, Tools>Options>Editor, ‘Auto List Members’ should be selected/checked. For instance, the IntelliSense will pop up after you type range followed by a period viz. range.[Intellisense for a Range object Pops Up]. Refer Image 2 — properties of the Range object are indicated by the fingers and methods of the Range object are indicated by the green boxes/bricks. You can either type or else select from this pop-up list, the method or property you want to connect with the object.

Using With…End With Statement to refer to Objects

As explained earlier, to access an Object and its properties & methods, you have to use the object name. In your vba code you will often need to refer to an object multiple times, and each time you will have to use its name. Instead of using the object name every time, you can execute multiple code lines which repeatedly refer to an object, by using the With…End With Statement. You start the block with the first line as:- type the With keyword followed by the Object Name. Insert one or more code lines after the first line:- access the object’s members (its properties, methods, etc) by typing a period (dot) followed by the property or method name, and you need not specify the object name each time. Terminate the block with the end line:- «End With». Refer to the below example, which shows how to make your vba code more readible using a With Block, and with Nesting ie. Block within a Block:

‘use the With … End With statement to refer to a Range object
With Worksheets(«Sheet1»).Range(«A1»)

‘use the Value property of the Range object, to set the value for the range:
.Value = 11
‘use the Name property, of the Range object, to set the range name:
.Name = «Score»

‘use the Font Property of the Range object that returns a Font object, and then use the With … End With statement to refer to the Font object
With .Font

‘note that because you are using the With … End With statement to refer to the Font object within the Range object, you will not refer to both the range or font objects below:
‘use the Name property of the Font object to set the font name:
.Name = «Arial»
‘use the Bold property of the Font object to set the font to bold:
.Bold = True
‘use the Color property of the Font object to set the font color:

.Color = vbRed

‘use the Borders property of the Range object to return all four borders (Borders collection object), and then use the LineStyle property of the Borders object to add a double border:
.Borders.LineStyle = xlDouble

‘the Clear Method of the Range object, clears the range (clears the contents, formulas and formatting):

End With

Using Variables in VBA

A variable is a named storage location used to store temporary values or information for use in execution of the code. In your vba program, a variable stores data and its content is used or changed later while executing the code. By declaring a variable for use in your code, you tell the Visual Basic compiler the variable’s data type (type of value it represents viz. integer, decimal, text, boolean, etc.) and other information such as its scope/level (what code can access it — variables can be Procedure Level, Module Level or can have a Public scope). Variables must be explicitly declared using the Dim, Private, Public, ReDim, or Static statements. When you declare variables by using a Dim statement (Dim is short for dimension): for declaring a variable to hold an Integer value, use «Dim rowNumber As Integer»; for declaring a variable to hold text values, use «Dim strEmployeeName As String»; and so on.

Keywords in VBA

Keywords are reserved words that VBA uses as part of its programming language. Keywords are words or commands that are recognized by VBA and can be used in vba code only as part of the vba language (like in a statement, function name, or operator) and not otherwise (like sub-procedure or variable names). Examples of keywords are: Sub, End, Dim, If, Next, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, and so on. To get help on a particular keyword, insert your mouse cursor within the keyword (in your vba code in VBE ) and press F1. Note that Keywords get capitalized in the vba code indicating that they have been written correctly viz. typing next will automatically appear as Next.

Assign an Object to a Variable, using the Set Keyword

In VBA, you use the Set keyword to assign an object reference. To assign an object to a variable in your vba code, you need to use the Set keyword as shown below. Note that using the Dim, Private or Public statements you only declare a variable as to its data type (type of value it represents viz. integer, text, etc.) and other information such as its scope/level (what code can access it). The actual object is assigned or referred to it only by using the Set statement. It is shorter to use an object variable & also more convenient because its data type will be known by VBA so that when you type the variable followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense).

Example: With the following code, we declare a variable (myRange) of Range data type, and then assign the Range object to this variable using the Set keyword, so that every time you want to refer to the specific Range, you can do so by using the variable. The following will enter the value 10 in cells A1 to C3 in the worksheet named «Sheet1».

Dim myRange As Range

Set myRange = Worksheets(«Sheet1»).Range(«A1:C3»)
myRange.Value = 10

Like this post? Please share to your friends:
  • Excel vba is value in array
  • Excel vba number from string
  • Excel vba is nothing is not nothing
  • Excel vba number format number
  • Excel vba is not numeric