Refers to range excel

Excel VBA Tutorial about the Range Object and cell rangesWhat is the first thing that comes to your mind when thinking about Excel?

In my case, it’s probably cells. After all, most of the time we spend working with Excel, we’re working with cells. Therefore, it makes sense that, when using Visual Basic for Applications for purposes of becoming more efficient users of Excel, one of the topics we must learn is how to work with cells within the VBA environment.

This VBA tutorial provides a basic explanation of how to work with cells using Visual Basic for Applications. More precisely, in this particular post I explain all the basic details you need to know to work with Excel’s VBA Range object. Range is the object that you use for purposes of referencing and working with cells within VBA.

However, the importance of Excel’s VBA Range object doesn’t end with the above. A substantial amount of the work you carry out with Excel involves the Range object. The Range object is one of the most commonly used objects in Excel VBA.

Despite the importance of Excel’s VBA Range, creating references to objects is generally one of the most confusing topics for users who are beginning to work with macros and Visual Basic for Applications. In the case of cell ranges, this is (to a certain extent) understandable, since VBA allows you to refer to ranges in many different ways.

The fact remains that, regardless of how confusing the topic of Excel’s VBA Range object may be, you must master it in order to become a macro and VBA expert. My main purpose with this VBA tutorial is to help you understand the basic matters surrounding this topic and illustrate the most common ways in which you can refer to Excel’s VBA Range object using Visual Basic for Applications.

More precisely, in this post you’ll learn about the following topics related to Excel’s VBA Range object:

Let’s start by taking a more detailed look at…

What Is Excel’s VBA Range Object

Excel’s VBA Range is an object. Objects are what is manipulated by Visual Basic for Applications.

More precisely, you can use the Range object to represent a range within a worksheet. This means that, by using Excel’s VBA Range object, you can refer to:

  • A single cell.
  • A row or a column of cells.
  • A selection of cells, regardless of whether they’re contiguous or not.
  • A 3-D range.

As you can see from the above, the size of Excel’s VBA Range objects can vary widely. At the most basic level, you can be making reference to a single (1) cell. On the other extreme, you have the possibility of referencing all of the cells in an Excel worksheet.

Despite this flexibility when referring to cells within a particular Excel worksheet, Excel’s VBA Range object does have some limitations. The most relevant is that you can only use it to refer to a single Excel worksheet at a time. Therefore, in order to refer to ranges of cells in different worksheets, you must use separate references for each of the worksheets.

How To Refer To Excel’s VBA Range Object

One of the first things you’ll have to learn in order to master Excel’s VBA Range object is how to refer to it. The following sections explain the most relevant rules you need to know in order to craft appropriate references.

The first few sections cover the most basic way of referring to Excel’s VBA Range object: the Range property. This is also how the macro recorder generally refers to the Range object.

However, further down, you’ll find some additional methods to create object references, such as using the Cells or Offset properties.

These are, however, not the only ways to refer to Excel’s VBA Range objects. There are a few more advanced methods, such as using the Application.Union method, which I don’t cover in this beginners VBA tutorial.

You may be wondering, which way is the best for purposes of referring to Excel’s VBA Range object?

Generally, the best method to use in order to craft a reference to Excel’s VBA Range object depends on the context and your specific needs.

Introduction To Referencing Excel’s VBA Range Object And The Object Qualifier

In order to be able to work appropriately with Range objects, you must understand how to work with the 2 main parts of a reference to Excel’s VBA Range object:

  • The object qualifier. This makes reference, more generally, to the general rules to creating object references. I cover this topic thoroughly here.
  • The relevant property or method that you’re using for purposes of returning a Range object. This makes reference, more generally, to the specific rules that apply to referring to Excel’s VBA Range object.

This VBA tutorial focuses on the second element above: the main properties you can use in order to refer to Excel’s VBA Range object.

Nonetheless, I explain a few key points regarding object referencing below. If you’re interested in learning more about the general rules that apply to object references, please refer to Excel VBA Object Model And Object References: The Essential Guide, which you can find in the Archives.

Introduction To Fully Qualified VBA Object References

Objects are capable of acting as containers for other objects.

At a basic level, when referencing a particular object, you tell Excel what the object is by referencing all of its parents. In other words, you go through Excel’s VBA object hierarchy.

You move through Excel’s object hierarchy by using the dot(.) operator to connect the objects at each of the different levels.

These types of specific references are known as fully qualified references.

How does a fully qualified reference look in the case of Excel’s VBA Range object?

The object at the top of the Excel VBA object hierarchy is Application. Application itself contains other objects.

Excel’s VBA Range object is contained within the Worksheet object. More precisely:

  • The Worksheet object has a Range property (Worksheet.Range).
  • The Worksheet.Range property returns a Range object.

The parent object of Worksheets is the Workbook object. Workbooks itself is contained within the Application object.

The hierarchical relationship between these different objects looks as follows:

Excel's VBA Range object reference

Therefore, the basic structure you must use to refer to Excel’s VBA Range object is the following:

Application.Workbooks.Worksheets.Range

You’ll notice that a few things within the basic structure described above are ambiguous. In particular, you’ll notice that this doesn’t specify the particular Excel workbook or worksheet that you’re referring to. In order to do this, you must understand…

How To Refer To An Object From A Collection

Within Visual Basic for Applications, an object collection is a group of related objects.

Both Workbooks and Worksheets, which are used to create a fully qualified reference to Excel’s VBA Range object, are examples of collections. There are 2 basic ways to refer to a particular object within a collection:

  • Use the VBA object name. In this case, the syntax is “Collection_name(“Object_name”)”.
  • Use an index number instead of the object name. If you choose this option, the basic syntax is “Collection_name(Index_number)”.

Notice how, in the first method you must use quotations (“”) within the parentheses. If you use the second method, you don’t have to surround the Index_number with quotes.

Let’s assume, then, that you want to work with the Worksheet named “Sheet1” within the Workbook “Book1.xlsm”. Depending on which of the 2 methods to refer to an object within a collection you use, the reference looks different.

If you create the reference using the VBA object name, the reference looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range

Whereas if you decide to use an index number, the reference is the following:

Application.Workbooks(1).Worksheets(1).Range

I usually use the first option when working with Visual Basic for Applications. Therefore, this is the method that I use in the examples throughout this VBA tutorial.

Simplifying Fully Qualified Object References

Excel’s VBA object model contains some default objects. These are assumed unless you enter something different.

You can simplify fully qualified object references by relying on these default VBA objects. I don’t generally suggest doing this blindly, as it involves some dangers.

There are 2 main types of default objects that you can use for purposes of simplifying fully qualified object references:

  • The Application object.
  • The active Workbook and Worksheet objects.

The Application object is always assumed. In other words, Visual Basic for Applications always assumes that you’re working with Excel itself. Therefore, you can simplify your fully qualified object references by omitting the Application. For example, in the cases that I use as an example above, the simplified references are as follows:

Workbooks("Book1.xlsm").Worksheets("Sheet1").Range
Workbooks(1).Worksheets(1).Range

Additionally, VBA assumes that you’re working with the current active workbook and active worksheet. This simplification is trickier than the previous one because it relies on you correctly identifying the active workbook and worksheet. As you’ll imagine, this is slightly more difficult than identifying the Excel application itself 😉 .

However, you can also use these 2 default objects for creating even simpler VBA object references. Continuing with the same examples above, these become:

Range

This brings us to the end of the introduction to the general rules to creating VBA object references. This summary has explained how to create fully qualified references and simplify them for purposes of creating the object qualifier that you use when crafting references to Excel’s VBA Range object.

The following sections focus on the specific rules that you can apply for purposes of referring to Excel’s VBA Range object. These are the most commonly used properties for returning a Range object.

How To Refer To Excel’s VBA Range Object Using The Range Property

The sections above explain, to a certain extent, the basic rules that you can apply to refer to Excel’s VBA Range object. Let’s start by recalling the 2 methods you can use to create a fully qualified reference if you’re working with the worksheet called “Sheet1” within the workbook named “Book1.xlsm”.

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range
Application.Workbooks(1).Worksheets(1).Range

You need to specify the particular range you want to work with. In other words, just using “Range” as it still appears in the examples above, isn’t enough.

Perhaps the most basic way to refer to Excel’s VBA Range object is by using the Range property. When applied, this property returns a Range object which represents a cell or range of cells.

There are 2 versions of the Range property: the Worksheet.Range property and the Range.Range property. The logic behind both of them is the substantially the same. The main difference is to which object they’re applied:

  • In the case of the Worksheet.Range property, the Range property is applied to a worksheet.
  • When using the Range.Range property, Range is applied to a range.

In other words, the Range property can be applied to 2 different types of objects:

  • Worksheet objects.
  • Range objects.

In the sections above, I explain how to create fully qualified object references. You’ve probably noticed that, in all of the examples above, the parent of Excel’s VBA Range object is the Worksheet object. In other words, in these cases, the Range property is applied to a Worksheet object.

However, you can also apply the Range property to a Range object. If you do this, the object returned by the Range property changes.

The reason for this, as explained by Microsoft, is that the Range.Range property acts in relation to the object to which it is applied to. Therefore, if you apply the Range.Range property, the property acts relative to the Range object, not the worksheet.

This means that you can apply the Range.Range property for purposes of referencing a range in relation to another range. I provide examples of how such a reference works below.

Basic Syntax Of The Range Property

The basic syntax that you can use to refer to Excel’s VBA Range object is “expression.Range(“Cell_Range”)”. You’ll notice that this syntax follow the general rules that I explain above for other VBA objects such as Workbooks and Worksheets. In particular, you’ll notice that there are 4 basic elements:

  • Element #1: The keyword “Range”.
  • Element #2: Parentheses that follow the keyword.
  • Element #3: The relevant cell range. I explain different ways in which you can define the range below.
  • Element #4: Quotations. The Cell_Range to which you’re making reference is generally within quotations (“”).

In this particular case, “expression” is simply a variable representing a Worksheet object (in the case of the Worksheet.Range property) or a Range object (for the Range.Range object).

Perhaps the most interesting item in the syntax of the Range property is the Cell_Range.

Let’s take a look at some of its characteristics…

In very broad terms, you can usually make reference to Cell_Range in a similar way to the one you use when writing a regular Excel formula. This means using A1-style references. However, there are a few important particularities, which I introduce in this section.

Don’t worry if everything seems a little bit confusing at first. I show some sample references in the following sections in order to make everything clear.

You can use 2 different syntaxes to define the range you want to work with:

Syntax #1: (“Cell1”)

This is the minimum you must include for purposes of defining the relevant cell range. As a general rule, when you use this syntax, the argument (Cell1) must be either of the following:

  • A string expressing the cell range address.
  • The name of a named cell range.

When naming a range, you can use any of the following 3 operators:

  • Colon (:): This is the operator you use to set up arrays. In the context of referring to cell ranges, you can use to refer to entire columns or rows, ranges of contiguous cells or ranges of noncontiguous cells.
  • Space ( ): This is the intersection operator. As shown below, you can use the intersection operator for purposes of referring to cells that are common to 2 separate ranges.
  • Comma (,): This is the union operator, which you can use to combine several ranges. As shown in the example below, you can use this operator when working with ranges of noncontiguous cells.

Syntax #2: “(Cell1, Cell2)”

If you choose to use this syntax, you’re basically delineating the relevant range by naming the cells in 2 of its corners:

  • “Cell1” is the cell in the upper-left corner of the range.
  • “Cell2” is the cell in the lower-right corner of the range.

However, this syntax isn’t as restrictive as it may seem at first glance. In this case, arguments can include:

  • Range objects;
  • Cell range addresses;
  • Named cell range names; or
  • A combination of the above items.

Let’s take a look at some specific applications of the Range property:

How To Refer To A Single Cell Using The Worksheet.Range Property

If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.

Example of how to refer to single cell with Worksheet.Range property

We can take it a step further and create a fully qualified reference for this single cell, assuming that we continue to work with Sheet1 within Book1.xlsm:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1")

You’ve probably noticed something very important:

There is no such thing as a Cell object. Cell is not an object by itself. Cells are contained within the Range object.

Perhaps even more accurately, cells are a property. Properties are the characteristics that you can use to describe an object. I cover the topic of object properties here.

You can actually use this property (Cells) to refer to a range. I explain how you can do this below.

The example above applies the Range property to a Worksheet object. In other words, it is an example of the Worksheet.Range property.

Now let’s take a look at what happens if the Range property is applied to a Range object:

How To Refer To A Single Cell In Relation To Another Range Using The Range.Range Property

Let’s assume, that instead of specifying a fully qualified reference as above, you simply use the Selection object as follows:

Selection.Range("A1")

Further, let’s assume that the current selection is the cell range between C3 and D5 (cells C3, C4, C5, D3, D4 and D5) of the active Excel worksheet. This selection is a Range object.

Example Range object in Excel

Since the Selection object represents the current selected area in the document, the reference above returns cell C3. It doesn’t return cell A1, as the previous fully qualified reference.

Example of referring to single cell with VBA Range.Range property

The reason for the different behavior of the 2 sample references above is because the Range property behaves relative to the object to which it is applied. In other words, when the Range property is applied to a Range object, it behaves relative to that Range (more precisely, its upper-left corner). When it is applied to a Worksheet object, it behaves relative to the Worksheet.

Creating references by applying the Range property to a Range object is not very straightforward. I personally find it a little confusing and counterintuitive.

However, the ability to refer to cells in relation to other range has several advantages. This allows you to (for example) refer to a cell without knowing its address beforehand.

Fortunately, there are alternatives for purposes of referring to a particular cell in relation to a range. The main one is the Range.Offset property, which I explain below.

How To Refer To An Entire Column Or Row Using The Worksheet.Range Property

Excel’s VBA Range objects can consist of complete rows or columns. You can refer to an entire row or column as follows:

  • Row: “Range(“Row_Number:Row_Number”)”.
  • Column: “Range(“Column_Letter:Column_Letter”)”.

For example, if you want to refer to the first row (Row 1) of a particular Excel worksheet, the syntax is “Range(“1:1″)”.

Excel's VBA Range object reference example entire row

If, on the other hand, you want to refer to the first column (Column A), you type “Range(“A:A”).

Excel's VBA Range object reference example: Entire column

Assuming that you’re working with Sheet 1 within Book1.xlsm, the fully qualified references are as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("1:1")
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A:A")

How To Refer To A Range Of Contiguous Cells Using The Worksheet.Range Property

You can refer to a range of cells by using the following syntax: “Range(“Cell_Range”). I describe how you can use 2 different syntaxes for purposes of referring to these type of ranges above:

  • By identifying the full range.
  • By delineating the range, naming the cells in its upper-left and lower-right corners.

Let’s take a look at how both of these look like in practice:

If you want to make reference to a range of cells between cells A1 and B5 (A1, A2, A3, A4, A5, B1, B2, B3, B4 and B5), one appropriate syntax is “Range(“A1:B5″)”. Continuing to work with Sheet1 within Book1.xlsm, the fully qualified reference is as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:B5")

Object reference example: Range

However, if you choose to apply the second syntax, where you delineate the relevant range, the appropriate syntax is “Range(“A1”, “B5″)”. In this case, the fully qualified reference looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1", "B5")

How To Refer To A Range Of NonContiguous Cells Using The Worksheet.Range Property

The syntax for purposes of referring to a range of noncontiguous cells in Excel is very similar to that used to refer to a range of contiguous cells. You simply separate the different areas by using a comma (,). Therefore, the basic syntax is “Range(“Cell_Range_1,Cell_Range_#,…”)”.

Let’s assume that you want to refer to the following ranges of noncontiguous cells:

  • Cells A1 to B5 (A1, A2, A3, A4, A5, B1, B2, B3, B4 and B5).
  • Cells D1 to D5 (D1, D2, D3, D4 and D5).

You refer to such range by typing “Range(“A1:B5,D1:D5″)”. In this case, the fully qualified reference looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:B5,D1:D5")

Excel's VBA Range object reference example: Non-contiguous cells

However, when working with ranges of noncontiguous cells, you may want to process each of the different areas separately. The reason for this is that some methods/properties have issues when working with such noncontiguous cell ranges.

You can handle the separate processing with a loop.

How To Refer To The Intersection Of 2 Ranges Using The Worksheet.Range Property

I describe how, when using the Range property, you can use 3 operators for purposes of identifying the relevant Range above. We’ve already gone through examples that use the colon (:) and comma (,) operators. These were used in the previous sections for purposes of referring to ranges of contiguous or noncontiguous cells.

The third operator, space ( ), is useful when you want to refer to the intersection of 2 ranges. The reason for this is clear:

The space ( ) operator is, precisely, the intersection operator.

Let’s assume that you want to refer to the intersection of the following 2 ranges:

  • Cells B1 to B10 (B1, B2, B3, B4, B5, B6, B7, B8, B9 and B10).
  • Cells A5 to C5 (A5, B5 and C5).

Screenshot of intersection of 2 Range objects

In this case, the appropriate syntax is “Range(“B1:B10 A5:C5″)”. When working with Sheet1 of Book1.xlsm, a fully qualified reference can be constructed as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("B1:B10 A5:C5")

Such a reference returns the cells that are common to the 2 ranges. In this particular case, the only cell that is common to both ranges is B5.

Excel's VBA object reference example: Intersection

How To Refer To A Named VBA Range Using The Worksheet.Range Property

If you’re referring to a VBA Range that has a name, the syntax is very similar to the basic case of referring to a single cell. You simply replace the address that you use to refer to the range with the appropriate name.

For example, if you want to create a reference to a VBA Range named “Excel_Tutorial_Example”, the appropriate syntax is “Range(“Excel_Tutorial_Example”)”. In this case, a fully qualified reference looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("Excel_Tutorial_Example")

Excel's VBA Range object reference: Named range

Remember to use quotation marks (“”) around the name of the range. If you don’t use quotes, Visual Basic for Applications interprets it as a variable.

How To Refer To Merged Cells Using The Worksheet.Range Property

In general, working with merged cells isn’t that straightforward. In the case of macros this is no exception. The following are some of the (potential) challenges you may face when working with a range that contains merged cells:

  • The macro behaving differently from what you expected.
  • Issues with sorting.

I may cover the topic of working with merged cells in future tutorials. For the moment, I explain how to refer to merged cells using the Range property. This should help you avoid some of the most common pitfalls when working with merged cells.

The first thing to consider when referring to merged cells is that you can reference them in either of the following 2 ways:

  • By referring to the entire merged cell range.
  • By referring only to the upper-left cell of the merged range.

Let’s assume that you’re working on an Excel spreadsheet where the cell range from A1 to C5 is merged. This includes cells A1, A2, A3, A4, A5, B1, B2, B3, B4, B5, C1, C2, C3, C4 and C5. In this case, the appropriate syntax is either of the following:

  • If you refer to the entire merged range, “Range(“A1:C5″)”. In this case, the fully qualified reference is “Application.Workbooks(“Book1.xlsm”).Worksheets(“Sheet1”).Range(“A1:C5″)”.
  • If you refer only to the upper-left cell of the merged range, “Range(“A1″)”. The fully qualified reference under this method is “Application.Workbooks(“Book1.xlsm”).Worksheets(“Sheet1”).Range(“A1″)”.

In both cases, the result is the same.

Excel's VBA Range object reference: Merged cells

You should be particularly careful when trying to assign values to merged cells. Generally, you can only carry this operation by assigning the value to the upper-left cell of the range (cell A1 in the example above). Otherwise, Excel VBA (usually) doesn’t:

  • Carry out the value assignment; and
  • Return an error.

How To Refer To A VBA Range Object Using Shortcuts For The Range Property

References to Excel’s VBA Range object using the Range property can be made shorter using square brackets ([ ]).

You can use this shortcut as follows:

  • Don’t use the keyword “Range”.
  • Surround the relevant property arguments with square brackets ([ ]) instead of using parentheses and double quotes (“”).

Let’s take a look at how this looks in practice by applying the shortcut to the different cases and examples shown and explained in the sections above.

Shortcut #1: Referring To A Single Cell

Instead of typing “Range(“Cell”)” as explained above, type “[Cell]”.

For example if you’re making reference to cell A1, use “[A1]”. The fully qualified reference for cell A1 in Sheet1 of Book1.xlsm looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[A1]

Excel's VBA Range object reference: Single cell with shortcut

Shortcut #2: Referring To An Entire Row Or Column

In this case, the usual syntax is either “Range(“Row_Number:Row_Number”)” or “Range(“Column_Letter:Column_Letter”)”. I explain this above.

By applying square brackets, you can shorten the references to the following:

  • Row: “[Row_Number:Row_Number]”.
  • Column: “[Column_Letter:Column_Letter]”.

For example, if you’re referring to the first row (Row 1) or the first column (Column A) of an Excel worksheet, the syntax is as follows:

And the fully qualified references, assuming you’re working with Sheet1 of Book1.xlsm are the following:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[1:1]
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[A:A]

Shortcut #3: Referring To A Range Of Contiguous Cells

Generally, you refer to a range of cells by using the syntax “Range(“Cell_Range”)”. If you’re identifying the full range by using the colon (:) operator, as I explain above, you usually structure the reference as “Range(“Top_Left_Cell:Right_Bottom_Cell”)”.

You can shorten the reference to a range of contiguous cells by using square brackets as follows: “[Top_Left_Cell:Right_Bottom_Cell]”.

For example in order to refer to a range of cells between cells A1 and B5 (A1, A2, A3, A4, A5, B1, B2, B3, B4 and B5), you can type “[A1:B5]”. Alternatively, if you’re using a fully qualified reference and are working with Sheet1 of Book1.xlsm, the syntax is as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[A1:B5]

Excel's VBA Range object reference: Range using shortcut

Shortcut #4: Referring To A Range Of NonContiguous Cells

This case is fairly similar to the previous one, in which we made reference to a range of contiguous cells. However, in order to separate the different areas, you use the comma (,) operator, as explained previously. In other words, the basic syntax is usually “Range(“Cell_Range_1,Cell_Range_#,…”)”.

When using square brackets, you can simplify the reference above to “[Cell_Range_1,Cell_Range_#,…]”.

If you want to refer to the following ranges of noncontiguous cells:

  • Cells A1 to B5 (A1, A2, A3, A4, A5, B1, B2, B3, B4 and B5).
  • Cells D1 to D5 (D1, D2, D3, D4 and D5).

The syntax of a reference using square brackets is “[A1:B5,D1:D5]”. The fully qualified reference looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[A1:B5,D1:D5]

Excel's VBA Range object reference: Non-contiguous range with shortcut

Shortcut #5: Referring To The Intersection Of 2 Ranges

Generally, the syntax for referring to the intersection of 2 ranges uses the space operator and is “Range(“Cell_Range_1 Cell_Range_2″)”. When using square brackets, this becomes “[Cell_Range_1 Cell_Range_2]”.

Let’s go back to the example I use above and assume that you want to refer to the intersection of the following 2 ranges:

  • Cells B1 to B10 (B1, B2, B3, B4, B5, B6, B7, B8, B9 and B10).
  • Cells A5 to C5 (A5, B5 and C5).

You can create a reference using square brackets as follows: “[B1:B10 A5:C5]”. When working with Sheet1 of Book1.xlsm, the fully qualified reference is:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[B1:B10 A5:C5]

And this returns the only cell common to both ranges: B5.

Excel's VBA Range object reference: Intersection with shortcut

Shortcut #6: Referring To A Named VBA Range

As explained above, when referring to a VBA Range that has a name, you replace the address of the range with the relevant name. Therefore, the basic syntax is “Range(“Range_Name”)”.

When using square brackets, the logic is the same. Therefore, you can refer to a named range by typing “[Range_Name]”.

For example, when referring to a VBA Range named “Excel_Tutorial_Example”, the reference can be structures as “[Excel_Tutorial_Example]”. When using a fully qualified reference, it looks as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").[Excel_Tutorial_Example]

Excel's VBA Range object reference: Named range with shortcut

How To Refer To A VBA Range Object Using The Cells Property

There is no Cell object within Visual Basic for Applications. There is a Worksheet.Cells property and a Range.Cells property. You can use the Cells property to return a Range object representing the cells.

The main difference between both Cells properties is in connection with the object to which the property is applied to:

  • When using the Worksheet.Cells property, you’re applying the property to a Worksheet object.
  • When using the Range.Cells property, that property is applied to a Range object.

This is important because, depending on the context, the properties may return different cells. More precisely, when applying the Cells property to a Range object, you’re referring to a cell in relation to another range.

This probably sounds confusing, I agree. Don’t worry, as the explanation and examples below make this topic clear. The most important thing to remember is that the Cells property allows you to refer to a cell range.

Since the basic logic behind both properties (Worksheet.Cells and Range.Cells) is similar, I cover both at the same time.

There are several ways in which you can use the Cells property to refer to a Range object. I explain the main methods of doing this in the following sections.

Syntax Of The Cells Property

The basic syntax of the Cells property is “expression.Cells(Row_Number, Column_Number)”, where:

  • “expression” is a variable representing a VBA object. This VBA object can be either a worksheet (in the case of the Worksheet.Cells property) or a range (for the Range.Cells property).
  • “Row_Number” and “Column_Number” are the numbers of both the row and the column.
    • Is common to use numbers in both cases.
    • When using this syntax, you can also use a letter to refer to the column. In this case, wrap the letter in double quotes (“”). Other than the quotations (“”) (surrounding the letter), you don’t need to use other quotations in the same way as you do when using the Range property.

One of the main differences between the Range and the Cells properties is that the Cells property takes row and column numbers as arguments. You can see this reflected in the syntax described above.

There are additional possible ways to implement the Cells property. However, they’re secondary and I explain them below.

The Range object has a property called the Range.Item property, which I explain below. The reason why you can specify the Row_Number and Column_Number arguments immediately after the Cells keyword is that the Range.Item property is the default property of the Range object. This is the same reason why, as explained above, you can also use a letter wrapped in double quotes (“”) to refer to the column. If you’re interested in understanding the relationship between the Range.Item property and the Cells property, please refer to the relevant section below.

For the moment, let’s go back to some of the VBA Ranges that have appeared in previous examples and see how to refer to them using the Cells property.

How To Refer To A Single Cell Using The Worksheet.Cells Property

The most basic use case of the Cells property is referring to a single cell.

The fact that the Cells property can only be used (usually) for purposes of returning a range of 1 cell is one of the main characteristics that distinguishes the Cells from the Range property.

There is actually a way to use the Cells property for purposes of referring to larger cell ranges. However, this involves combining the Range and Cells properties. I explain this method below.

Referring to a single cell using the Cells property is relatively simple. For example, if you want to refer to cell A1 within Sheet1 of Book1.xlsm, the fully qualified reference is pretty much what you’d expect considering the basic syntax shown in the previous section:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Cells(1, 1)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Cells(1, "A")

Excel's VBA Range object reference: Single cell using Cells property

There is, however, a second way to create references to a single cell when using the Worksheet.Cells property. Let’s take a look at this…

Alternative Syntax For Referring To A Single Cell Using The Worksheet.Cells Property

The syntax of the Cells property that I describe above is probably the one that you’ll use the most in practice.

The following alternative is substantially the same as the syntax that I have explained above. It also starts with “expression.Cells”. The difference lies in the arguments that appear within the parentheses.

This alternative syntax is “expression.Cells(Cell_Index)”. In this particular case, there is only 1 argument: the index of the relevant cell.

The main question, then, is how does Visual Basic for Applications determine the index of a cell?

For these purposes, each and every cell is assigned a number. Cells are numbered from left to right and from top to bottom. In other words:

  • Numbering begins with the first row:
    • Cell A1 is assigned the number 1.
    • Cell B1 is assigned the number 2.
    • Cell C1 is assigned the number 3.
    • The process continues with each of the subsequence cells, until…
    • Cell XFD1 (the last cell in the first row) is assigned the number 16,384.
  • Once all the cells in the first row have been assigned a number, the process continues with the second row:
    • Cell A2 is assigned the number 16,385.
    • Cell B2 is assigned the number 16,386.
    • Cell C2 is assigned the number 16,387.
    • The number assignment continues until…
    • Cell XFD2 (the last cell in the second row) is assigned the number 32,768.
  • The process continues with the third row.
  • Then the fourth row.
  • And so on, until…
  • It reaches row 1,048,576.
  • And…
  • The last cell in an Excel worksheet (cell XFD1048676) is assigned the number 17,179,869,184.

The following screenshot gives you an idea of how this number assignment goes:

Cell_Index assignment in Excel worksheet

For example, if you want to refer to cell A2 using this syntax, the appropriate reference is “Cells(16385)”. A fully qualified reference for cell A2 in Sheet1 of Book1.xlsm is as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Cells(16385)

Excel's VBA Range object reference: Single cell with Cells property

The initial 2 examples of the Cells property, show how it is applied to a Worksheet object. However, you can also use this syntax to apply the property to a Range object. This allows you to refer to a cell relative to another range.

How To Refer To A Single Cell In Relation To A Range Using The Range.Cells Property

Assume that the current selection is a range covering cells C3 through D5 (cells C3, C4, C5, D3, D4 and D5) of the active Excel worksheet. You already know that this is a Range object.

Example of VBA Range object

We can use the Selection property to create the following reference:

Selection.Cells(1, 1)

This reference returns cell C3 itself.

Excel's VBA Range object: Single cell in reference to range

This is different from what the previous example (a fully qualified reference) returned (cell A1).

The reason for the different behaviors seen in the examples above is that the Range property behaves relative to the object to which it is applied (a worksheet or a range). In the case of cell ranges (such as the example above), the Range property behaves in relation to the upper-left corner of the range. The logic is the same that explains the different behaviors when applying the Range property to a Worksheet object or a Range object.

Similarly, you can create references to a single cell in relation to a range using the alternative syntax of the Cells property that I described above. Let’s take a look at this case:

Alternative Syntax For Referring To A Single Cell In Relation To A Range Using The Range.Cells Property

To recall, the alternative syntax is “expression.Cells(Cell_Index)”.

In such case:

  • Each of the cells within the range is assigned a number.
  • The assignment is carried out following the same pattern described above for the whole worksheet. From left to right and from top to bottom.

For example, let’s assume that you are working with the cell range from A1 to B10 and want to select cell A5.

Example of a VBA Range object

In this case, the reference is “Range(“A1:B10″).Cells(9)”. The following screenshot shows the way the Cell_Index numbers are assigned to the cells within the relevant range:

Cell_Index number assignment within range

A fully qualified reference, when working with Sheet1 of Book1.xlsm is as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:B10").Cells(9)

Excel's VBA Range object: Single cell within range

An interesting aspect of applying this syntax of the Cells property to a Range object is that the argument for the Cells property is not limited by the number of cells in the referenced range. If you use a number that is larger than the amount of cells in the relevant range, Visual Basic for Applications continues counting as if the range was taller (extending to the bottom) than it’s in reality. In other words: The Range object returned by the Cells property doesn’t have to be inside the original/source cell range.

In the case of the range described in the example above (A1:B10), the Cell_Index assignment continues as shown in the following screenshot:

Cell_Index assignment with a cell range

For example, the cell range from A1 to B10 contains 20 cells. Let’s assume that you type “21” as an argument for the Cells property. The resulting reference is “Range(“A1:B10″).Cells(21)”. The fully qualified reference is:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:B10").Cells(21)

This statement makes reference to cell A11 which is outside the originally referenced range (A1:B10).

Excel's VBA Range object reference: Cell outside range

How To Refer To A Cell Range Using The Range And Cells Properties

As anticipated above, you can combine the Range and Cells properties to refer to cell ranges. Perhaps the easiest way to do this is to use the Cells property as a parameter of the Range property.

For these purposes, use the following syntax: “Range(Cells(Row_Number_First_Cell, Column_Number_First_cell), Cells(Row_Number_Last_Cell, Column_Number_Last_Cell))”.

For example, if you want to refer to a range covering cells A1 to B5 (A1, A2, A3, A4, A5, B1, B2, B3, B4 and B5) in Sheet1 of Book1.xlsm using the Cells property, you’d type “Range(Cells(1, 1), Cells(5, 2)). The corresponding fully qualified reference is as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range(Cells(1, 1), Cells(5, 2))

Excel's VBA Range object: Range using Cells property

This technique is useful (for example) when you use variables to specify the parameters of the Cells property. This can happen, for example, when looping.

How To Refer To All The Cells In A Worksheet Using The Worksheet.Cells Property

This is probably the simplest, but also most limited, way to implement the Cells property. The statement “expression.Cells” returns absolutely all of the cells in the relevant Excel worksheet.

For example, the following statement returns absolutely all of the cells of Sheet1 in Book1.xlsm:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Cells

This method doesn’t allow you to reference a single cell.

Why You Should Learn To Use The Cells Property To Refer To Excel’s VBA Range Object

Using the Cells property may seem like a slightly more complicated way to refer to Excel’s VBA Range object than using the Range property. However there are some scenarios where using the Cells property may be more appropriate.

Perhaps the most important scenario in which the Cells property shows its usefulness is when you’re using variables instead of the actual numbers as the arguments for the Cells property. In practice, you’re likely to find yourself in this situation (using variables instead of hardcoded numbers as arguments of the Cells property) often.

The Cells property and the ability to use variables as arguments is helpful when carrying out certain activities with Visual Basic for Applications. A common case of such an activity is looping (a topic I cover here).

How To Refer To A VBA Range Object Using The Range.Offset Property

Just as the previously explained properties, the Range.Offset property also returns a Range object.

However, in the case of the Range.Offset property, the Range object returned is that located a certain number of rows and columns from a specified range.

In other words, the returned Range object is determined by the following factors:

  • A base range, which is going to be the base of the offset.
  • The number of rows by which the base range is to be offset.
  • The number of columns by which the base range is to be offset.

The syntax of the Range.Offset property reflects these 3 elements. This syntax is “expression.Offset(Row_Offset, Column_Offset)”, where:

  • “expression” is a variable representing a VBA Range object.
  • “Row_Offset” is the number of rows by which the range is to be offset. This value can be either positive (offset is done downwards) or negative (offset is done upwards).
  • “Column_Offset” is the number of columns by which the range is to be offset. In the case of positive values, the offset is made to the right. When using negative values, the offset is made to the left.

Both the Row_Offset and the Column_Offset arguments carry the offset from the upper-left cell of the VBA Range object represented by “expression”.

The way the Offset property works means that it can only be applied to a Range object. In other words, there is no Worksheet.Offset property. This means that this property is a great alternative for purposes of referring to a particular cell in relation to a range without using the more complicated methods that I explain above, namely applying the Range or the Cells properties to a Range object.

Let’s look at a few examples of how to use the Range.Offset property to refer to a VBA Range object:

How To Refer To A Single Cell Using The Range.Offset Property

In the simplest case, you can use Range.Offset for referring to a single cell as follows:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Offset(RowOffset:=1, ColumnOffset:=1)

You can simplify this statement by omitting the keywords “RowOffset” and “ColumnOffset”. The resulting reference is the following:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Offset(1, 1)

In this particular case, Visual Basic for Applications returns a cell that is 1 row below and 1 column to the right of cell A1. In other words, the base range is cell A1.

Excel's VBA Range object: Single cell

And, from there, VBA moves 1 row down and 1 column to the right. Therefore, the above reference, refers to cell B2.

Excel's VBA Range object: Single cell with Offset property

In certain cases, you may want to create a relative reference in which the Range.Offset property only needs to move a certain number of rows or columns (but not both) to find the cell it should return. In these cases, you can simply omit the irrelevant argument.

For example, the following statements refer to a cell one row below the cell A1. In other words, it refers to cell A2:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Offset(RowOffset:=1)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Offset(1)

Excel's VBA Range object: Single cell with Offset property

Similarly, the following statements refer to cell B1, which is one column to the right of cell A1:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Offset(ColumnOffset:=1)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Offset(, 1)

Excel's VBA Range object: Cell with Offset property

Let’s take a look at a different way to refer to the base range. The following statement also refers to a single cell. However, notice the difference in the way the base cell for the offset is expressed.

ActiveCell.Offset(1, 1)

In this case, instead of using “Range”, I use the Application.ActiveCell property. This property returns a Range object that represents the current active cell.

Therefore, Visual Basic for Applications returns a cell that is 1 row below and 1 column to the right of the current active cell. For example, if the current active cell is A1, the statement above returns cell B2.

Excel's VBA Range object: Single cell with Offset property

The Range.Offset property generates an error if it is used for trying to return a cell that doesn’t exist. This may happen, for example, if the current active cell is A1 and you use the following reference:

ActiveCell.Offset(-1, -1)

The statement above is asking Visual Basic for Applications to return the cell that is 1 row above and 1 column to the left of cell A1. Since no such cell exists, an error is generated.

Visual Basic for Applications error message

How To Refer To A Range Of Cells Using The Range.Offset Property

You already know the different operators that you can use for purposes of referring to a range of cells using Visual Basic for Applications. Particularly important is the colon (:) operator, which you can use to set up arrays and create references to ranges of contiguous cells.

If you want to refer to a range of cells using the Range.Offset property, you can simply use the same colon operator in order to define the cell range that is the base of the offset.

The logic of the offset continues to be the same.

Take a look, for example, at the following VBA Range object reference:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:B5").Offset(3, 3)

This statement proceeds as follows:

  • It sets as base range that containing cells A1 through B5 (A1, A2, A3, A4, A5, B1, B2, B3, B4 and B5).
    excel vba object base range
  • It moves the range 3 cells to the right and 3 cells down.

As a consequence of the above, the statement returns the range from cells D4 to E8 (D4, D5, D6, D7, D8, E4, E5, E6, E7 and E8).

Excel's VBA Range object with Offset property

Why You Should Learn To Use The Range.Offset Property To Refer To Excel’s VBA Range Object

The Range.Offset property is (usually) most useful when:

  • You’re working with variables instead of actual numbers as arguments; and
  • In looping procedures.

The Range.Offset property is also commonly used by the macro recorder when you use relative references while recording a macro. Therefore, you can expect to encounter this type of reference structure constantly when working with macros and Visual Basic for Applications.

How To Refer To A VBA Range Object Using The Range.Item Property

For reasons that I explain at the end of this section, you may not end up using the Range.Item property too much in your day-to-day Excel work. However, you may still need to use this property from time to time. Additionally, having a good understanding of the Range.Item property is helpful for purposes of becoming a better user of the Cells property which I describe above and understanding its syntax.

Just as some of the other properties discussed throughout this VBA tutorial, the Range.Item property returns an object. The object is a range.

In this particular case, the range is determined by starting with a particular specified range. The Range.Item property then accesses a particular cell in that range, based on the arguments you use.

The syntax of the Range.Item property is very similar to those of the other properties covered by this VBA tutorial: “expression.Item(Row_Index,Column_Index)”. In this case, “expression” is a variable representing a Range object.

Notice, however, that in the case of the Range.Item property, I refer to “Row_Index” and “Column_Index”. In the case of most of the other properties covered in this VBA tutorial, the arguments made reference to either numbers (for example “Row_Number”) or letters (such as “Column_Letter”).

The only other time I use the word index for purposes of describing a property’s arguments is when explaining an alternative syntax for purposes of referring to a single cell with the Cells property. The reason why the Range.Item property uses index in order to identify both the row and column is because the behavior of the Row_Index argument is very similar to that of the Cell_Index argument in that use case of the Cells property.

Let’s take a closer look at this Row_Index argument. The main characteristics of this argument are the following:

  • It is required.
  • It must be a number.
  • It determines the cell that you access within the relevant range. For these purposes, there are 2 options.
    • If the only argument you’re using is Row_Index, cells are numbered from left to right and from top to bottom. I explain, in detail, how this works above.
    • If you’re using both Row_Index and Column_Index, Row_Index determines the row of the cell you access within the applicable range.

The other argument of the Range.Item property (Column_Index) behaves slightly different. The following are its main characteristics:

  • It’s optional.
  • It can be a number or a string. As a consequence of this characteristic you can use both the column number or the column letter (wrapped in quotations) to refer to a particular column. I show you how this works below.
  • It determines the column of the cell you access within the relevant range.

Both arguments are relative offsets. Visual Basic for Applications uses those arguments to determine how many rows and columns to move away from the originally specified range.

I explain (above) how, when applied to a Range object, the Cells property is not limited by the number of cells in the specified range. In other words, you can use the Cells property to refer to cells outside that range. The same thing happens with the Range.Item property.

After reading about the other properties above, you probably have a good idea about what the Range.Item property does. Nonetheless, let’s take a look at a couple of examples.

For example, the following statements all return cell A1 of Sheet1 in Book1.xlsm:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells.Item(1)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells.Item(1, 1)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells.Item(1, "A")

Excel's VBA Range object: Single cell with Item property

However, let’s assume that you want to refer to cell B8. For these purposes, you can use either of the following references:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells.Item(30)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells.Item(8, 2)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells.Item(8, "B")

Excel's VBA Range object: Single cell with Item property

Part of the importance of the Range.Item property is that it allows you to refer to a specific cell in relation to a range.

However, perhaps even more important for purposes of this VBA tutorial, the Item property is the default property for the Range object. You can generally omit the Item keyword before specifying the Row_Index and Column_Index arguments. In the case of the last example above, this results in the following shortened references:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells(30)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells(8, 2)
Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1:D10").Cells(8, "B")

The structure used in these references probably looks quite familiar by now. The reason for this is that this structure is substantially the same as that which I describe above when explaining the Cells property.

Due mainly to this reason, you’ll probably won’t use the Range.Item property too often. Instead, you’ll likely resort to the Cells property.

However, now you know that, if required for your purposes, you can use the Range.Item property for purposes of referring to Excel’s VBA Range objects.

Furthermore, having a good knowledge about the Range.Item property is helpful for, among others purposes:

  • Having a better understanding of the Cells property.
  • Crafting better references to Excel’s VBA Range objects with the Cells property.

Conclusion

The Range object is one of the most important and frequently used Excel VBA objects.

Unfortunately, the topic of Excel’s VBA Range object can sometimes be confusing for certain users. One of the main reasons for this is the fact that there are several different ways to refer to the Range object.

This VBA tutorial provides a brief introduction to the topic of Excel’s VBA Range object. Perhaps more importantly, this post explains and illustrates some of the most common methods for purposes of creating appropriate references to the Range object.

Now that you’ve read this post, you probably have a good understanding of Excel’s VBA Range object and won’t be confused by the different alternatives you can use to reference it. In particular, you’re probably now an expert when it comes to creating references to Range objects using any of the following properties:

  • Range.
  • Cells.
  • Offset.
  • Item.

There are still some other ways to refer to and manipulate Excel’s VBA Range objects. Some of these are the Application.Union method and the Range.Areas property.

What’s in the name?

If you are working with Excel spreadsheets, it could mean a lot of time saving and efficiency.

In this tutorial, you’ll learn how to create Named Ranges in Excel and how to use it to save time.

Named Ranges in Excel – An Introduction

If someone has to call me or refer to me, they will use my name (instead of saying a male is staying in so and so place with so and so height and weight).

Right?

Similarly, in Excel, you can give a name to a cell or a range of cells.

Now, instead of using the cell reference (such as A1 or A1:A10), you can simply use the name that you assigned to it.

For example, suppose you have a data set as shown below:

Creating Named Ranges in Excel - Dataset

In this data set, if you have to refer to the range that has the Date, you will have to use A2:A11 in formulas. Similarly, for Sales Rep and Sales, you will have to use B2:B11 and C2:C11.

While it’s alright when you only have a couple of data points, but in case you huge complex data sets, using cell references to refer to data could be time-consuming.

Excel Named Ranges makes it easy to refer to data sets in Excel.

You can create a named range in Excel for each data category, and then use that name instead of the cell references. For example, dates can be named ‘Date’, Sales Rep data can be named ‘SalesRep’ and sales data can be named ‘Sales’.

Creating Named Ranges in Excel - named ranges created

You can also create a name for a single cell. For example, if you have the sales commission percentage in a cell, you can name that cell as ‘Commission’.

Benefits of Creating Named Ranges in Excel

Here are the benefits of using named ranges in Excel.

Use Names instead of Cell References

When you create Named Ranges in Excel, you can use these names instead of the cell references.

For example, you can use =SUM(SALES) instead of =SUM(C2:C11) for the above data set.

Have a look at ṭhe formulas listed below. Instead of using cell references, I have used the Named Ranges.

  • Number of sales with value more than 500: =COUNTIF(Sales,”>500″)
  • Sum of all the sales done by Tom: =SUMIF(SalesRep,”Tom”,Sales)
  • Commission earned by Joe (sales by Joe multiplied by commission percentage):
    =SUMIF(SalesRep,”Joe”,Sales)*Commission

You would agree that these formulas are easy to create and easy to understand (especially when you share it with someone else or revisit it yourself.

No Need to Go Back to the Dataset to Select Cells

Another significant benefit of using Named Ranges in Excel is that you don’t need to go back and select the cell ranges.

You can just type a couple of alphabets of that named range and Excel will show the matching named ranges (as shown below):

Creating Named Ranges in Excel - Demo

Named Ranges Make Formulas Dynamic

By using Named Ranges in Excel, you can make Excel formulas dynamic.

For example, in the case of sales commission, instead of using the value 2.5%, you can use the Named Range.

Now, if your company later decides to increase the commission to 3%, you can simply update the Named Range, and all the calculation would automatically update to reflect the new commission.

How to Create Named Ranges in Excel

Here are three ways to create Named Ranges in Excel:

Method #1 –  Using Define Name

Here are the steps to create Named Ranges in Excel using Define Name:

This will create a Named Range SALESREP.

Method #2: Using the Name Box

  • Select the range for which you want to create a name (do not select headers).
  • Go to the Name Box on the left of Formula bar and Type the name of the with which you want to create the Named Range.How to Create Named Ranges in Excel - Name Box
  • Note that the Name created here will be available for the entire Workbook. If you wish to restrict it to a worksheet, use Method 1.

Method #3: Using Create From Selection Option

This is the recommended way when you have data in tabular form, and you want to create named range for each column/row.

For example, in the dataset below, if you want to quickly create three named ranges (Date, Sales_Rep, and Sales), then you can use the method shown below.

Creating Named Ranges in Excel - Dataset

Here are the steps to quickly create named ranges from a dataset:

This will create three Named Ranges – Date, Sales_Rep, and Sales.

Note that it automatically picks up names from the headers. If there are any space between words, it inserts an underscore (as you can’t have spaces in named ranges).

Naming Convention for Named Ranges in Excel

There are certain naming rules you need to know while creating Named Ranges in Excel:

  • The first character of a Named Range should be a letter and underscore character(_), or a backslash(). If it’s anything else, it will show an error. The remaining characters can be letters, numbers, special characters, period, or underscore.
  • You can not use names that also represent cell references in Excel. For example, you can’t use AB1 as it is also a cell reference.
  • You can’t use spaces while creating named ranges. For example, you can’t have Sales Rep as a named range. If you want to combine two words and create a Named Range, use an underscore, period or uppercase characters to create it. For example, you can have Sales_Rep, SalesRep, or SalesRep.
    • While creating named ranges, Excel treats uppercase and lowercase the same way. For example, if you create a named range SALES, then you will not be able to create another named range such as ‘sales’ or ‘Sales’.
  • A Named Range can be up to 255 characters long.

Too Many Named Ranges in Excel? Don’t Worry

Sometimes in large data sets and complex models, you may end up creating a lot of Named Ranges in Excel.

What if you don’t remember the name of the Named Range you created?

Don’t worry – here are some useful tips.

Getting the Names of All the Named Ranges

Here are the steps to get a list of all the named ranges you created:

This will give you a list of all the Named Ranges in that workbook. To use a named range (in formulas or a cell), double click on it.

Displaying the Matching Named Ranges

  • If you have some idea about the Name, type a few initial characters, and Excel will show a drop down of the matching names.How to Create Named Ranges in Excel - Named Range Suggest

How to Edit Named Ranges in Excel

If you have already created a Named Range, you can edit it using the following steps:

Useful Named Range Shortcuts (the Power of F3)

Here are some useful keyboard shortcuts that will come handy when you are working with Named Ranges in Excel:

  • To get a list of all the Named Ranges and pasting it in Formula: F3
  • To create new name using Name Manager Dialogue Box: Control + F3
  • To create Named Ranges from Selection: Control + Shift + F3

Creating Dynamic Named Ranges in Excel

So far in this tutorial, we have created static Named Ranges.

This means that these Named Ranges would always refer to the same dataset.

For example, if A1:A10 has been named as ‘Sales’, it would always refer to A1:A10.

If you add more sales data, then you would have to manually go and update the reference in the named range.

In the world of ever-expanding data sets, this may end up taking up a lot of your time. Every time you get new data, you may have to update the Named Ranges in Excel.

To tackle this issue, we can create Dynamic Named Ranges in Excel that would automatically account for additional data and include it in the existing Named Range.

For example, For example, if I add two additional sales data points, a dynamic named range would automatically refer to A1:A12.

Creating Named Ranges in Excel - Dynamic Named Ranges in Excel

This kind of Dynamic Named Range can be created by using Excel INDEX function. Instead of specifying the cell references while creating the Named Range, we specify the formula. The formula automatically updated when the data is added or deleted.

Let’s see how to create Dynamic Named Ranges in Excel.

Suppose we have the sales data in cell A2:A11.

Creating Named Ranges in Excel - Dynamic Data

Here are the steps to create Dynamic Named Ranges in Excel:

    1. Go to the Formula tab and click on Define Name.Dynamic Named Ranges Using INDEX Function in Excel - Defined Name
    2. In the New Name dialogue box type the following:
      • Name: Sales
      • Scope: Workbook
      • Refers to: =$A$2:INDEX($A$2:$A$100,COUNTIF($A$2:$A$100,”<>”&””))Name New dialog box to created a named range in Excel
    3. Click OK.

Done!

You now have a dynamic named range with the name ‘Sales’. This would automatically update whenever you add data to it or remove data from it.

How does Dynamic Named Ranges Work?

To explain how this work, you need to know a bit more about Excel INDEX function.

Most people use INDEX to return a value from a list based on the row and column number.

But the INDEX function also has another side to it.

It can be used to return a cell reference when it is used as a part of a cell reference.

For example, here is the formula that we have used to create a dynamic named range:

=$A$2:INDEX($A$2:$A$100,COUNTIF($A$2:$A$100,"<>"&""))

INDEX($A$2:$A$100,COUNTIF($A$2:$A$100,”<>”&””) –> This part of the formula is expected to return a value (which would be the 10th value from the list, considering there are ten items).

However, when used in front of a reference (=$A$2:INDEX($A$2:$A$100,COUNTIF($A$2:$A$100,”<>”&””))) it returns the reference to the cell instead of the value.

Hence, here it returns =$A$2:$A$11

If we add two additional values to the sales column, it would then return =$A$2:$A$13

When you add new data to the list, Excel COUNTIF function returns the number of non-blank cells in the data. This number is used by the INDEX function to fetch the cell reference of the last item in the list.

Note:

  • This would only work if there are no blank cells in the data.
  • In the example taken above, I have assigned a large number of cells (A2:A100) for the Named Range formula. You can adjust this based on your data set.

You can also use OFFSET function to create a Dynamic Named Ranges in Excel, however, since OFFSET function is volatile, it may lead a slow Excel workbook. INDEX, on the other hand, is semi-volatile, which makes it a better choice to create Dynamic Named Ranges in Excel.

You may also like the following Excel resources:

  • Free Excel Templates.
  • Free Online Excel Training (7-Part Online Video Course).
  • Useful Excel Macro Code Examples.
  • 10 Advanced Excel VLOOKUP Examples.
  • Creating a Drop Down List in Excel.
  • Creating a Named Range in Google Sheets.
  • How to Reference Another Sheet or Workbook in Excel
  • How to Delete Named Range in Excel?

Excel VBA Referencing Ranges — Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert

You can refer to or access a worksheet range using properties and methods of the 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. One of the most important aspects in vba coding is referencing and using Ranges within a Worksheet. This section (divided into 2 parts) covers various properties and methods for referencing, accessing & using ranges, divided under the following chapters.

Excel VBA Referencing Ranges — Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert:

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address;

Activate & Select Cells; the ActiveCell & Selection;

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method;

Excel VBA Refer to Ranges — Union & Intersect; Resize; Areas, CurrentRegion, UsedRange & End Properties; SpecialCells Method:

Ranges — Union & Intersect;

Resize a Range;

Referencing — Contiguous Block(s) of Cells, Range of Contiguous Data, Cells Meeting a Specified Criteria, Used Range, Cell at the End of a Block / Region, Last Used Row or Column;


Related Links:

Working with Objects in Excel VBA

Excel VBA Application Object, the Default Object in Excel

Excel VBA Workbook Object, working with Workbooks in Excel

Microsoft Excel VBA — Worksheets

Excel VBA Custom Classes and Objects


——————————————————————————————-

Contents:

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address

Activate & Select Cells; the ActiveCell & Selection

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method

——————————————————————————————-

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address

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. A Range object is always with reference to a specific worksheet, and Excel currently does not support Range objects spread over multiple worksheets.

Range object refers to a single cell:

Dim rng As Range
Set rng = Range(«A1»)

Range object refers to a block of contiguous cells:

Dim rng As Range
Set rng = Range(«A1:C3»)

Range object refers to a row:

Dim rng As Range
Set rng = Rows(1)

Range object refers to multiple columns:

Dim rng As Range
Set rng = Columns(«A:C»)

Range object refers to 2 or more blocks of contiguous cells — using the ‘Union method’ & ‘Selection’ (these have been explained in detail later in this section).

Union method:

Dim rng1 As Range, rng2 As Range, rngUnion As Range
‘set a contiguous block of cells as the first range:
Set rng1 = Range(«A1:B2»)
‘set another contiguous block of cells as the second range:
Set rng2 = Range(«D3:E4»)
‘assign a variable (range object) to represent the union of the 2 ranges, using the Union method:
Set rngUnion = Union(rng1, rng2)
‘set interior color for the range which is the union of 2 range objects:
rngUnion.Interior.Color = vbYellow

Selection property:

‘select 2 contiguous block of cells, using the Select method:
Range(«A1:B2,D3:E4»).Select
‘perform action (set interior color of cells to yellow) on the Selection, which is a Range object:
Selection.Interior.Color = vbYellow

Range property of the Worksheet object ie. Worksheet.Range Property. Syntax: WorksheetObject.Range(Cell1, Cell2). You have an option to use only the Cell1 argument and in this case it will have to be a A1-style reference to a range which can include a range operator (colon) or the union operator (comma), or the reference to a range can be a defined name. Examples of using this type of reference are Worksheets(«Sheet1»).Range(«A1») which refers to cell A1; or Worksheets(«Sheet1»).Range(«A1:B3») which refers to the cells A1, A2, A3, B1, B2 & B3. When both the Cell1 & Cell2 arguments are used (cell1 and cell2 are Range objects), these refer to the cells at the top-left corner and the lower-right corner of the range (ie. the start and end cells of the range), and these arguments can be a single cell, an entire row or column or a single named cell. An example of using this type of reference is Worksheets(«Sheet1»).Range(Cells(1, 1), Cells(3, 2)) which refers to the cells A1, A2, A3, B1, B2 & B3. Omitting the object qualifier will default to the active sheet viz. using the code Range(«A1») will return cell A1 of the active sheet, and will be the same as using Application.Range(«A1») or ActiveSheet.Range(«A1»).

Range property of the Range object: Use the Range.Range property [Syntax: RangeObject.Range(Cell1,Cell2)] for relative referencing ie. to access a range relative to a range object. For example, Worksheets(«Sheet1»).Range(«C5:E8»).Range(«A1») will refer to Range(«C5») and Worksheets(«Sheet1»).Range(«C5:E8»).Range(«B2») will refer to Range(«D6»).

Shortcut Range Reference: As compared to using the Range property, you can also use a shorter code to refer to a range by using square brackets to enclose an A1-style reference or a name. While using square brackets, you do not type the Range word or wrap the range in quotation marks to make it a string. Using square brackets is similar to applying the Evaluate method of the Application object. The Range property or the Evaluate method use a string argument which enables you to manipulate the string with vba code, whereas using the square brackets will be inflexible in this respect. Examples: using [A1].Value = 5 is equivalent to using Range(«A1»).Value = 5; using [A1:A3,B2:B4,C3:D5].Interior.Color = vbRed is equivalent to Range(«A1:A3,B2:B4,C3:D5»).Interior.Color = vbRed; and with named ranges, [Score].Interior.Color = vbBlue is equivalent to Range(«Score»).Interior.Color = vbBlue. Using square brackets only enables reference to fixed ranges which is a significant shortcoming. Using the Range property enables you to manipulate the string argument with vba code so that you can use variables to refer to a dynamic range, as illustrated below:

Sub DynamicRangeVariable()
‘using a variable to refer a dynamic range.

Dim i As Integer

‘enters the text «Hello» in each cell from B1 to B5:
For i = 1 To 5
Range(«B» & i) = «Hello»
Next

End Sub

The Cells Property returns a Range object referring to all cells in a worksheet or a range, as it can be used with respect to an Application object, a Worksheet object or a Range object. Application.Cells Property refers to all cells in the active worksheet. You can use the code Application.Cells or omit the object qualifier (this property is a member of ‘globals’) and use the code Cells to refer to all cells of the active worksheet. The Worksheet.Cells Property (Syntax: WorksheetObject.Cells) refers to all cells of a specified worksheet. Use the code Worksheets(«Sheet1»).Cells to refer to all cells of worksheet named «Sheet1». Use the Range.Cells Property ro refer to cells in a specified range — (Syntax: RangeObject.Cells). This property can be used as Range(«A1:B5»).Cells, however using the word cells in this case is immaterial because with or without this word the code will refer to the range A1:B5. To refer to a specific cell, use the Item property of the Range object (as explained in detail below) by specifying the relative row and column positions after the Cells keyword, viz. Worksheets(«Sheet1»).Cells.Item(2, 3) refers to range C2 and Worksheets(«Sheet1»).Range(«C2»).Cells(2, 3) will refer to range E3. Because the Item property is the Range object’s default property you can omit the Item word word and use the code Worksheets(«Sheet1»).Cells(2, 3) which also refers to range C2. You may find it preferable in some cases to use Worksheets(«Sheet1»).Cells(2, 3) over Worksheets(«Sheet1»).Range(«C2») because variables for the row and column can easily be used therein.

Item property of the Range object: Use the Range.Item Property to return a range as offset to the specified range. Syntax: RangeObject.Item(RowIndex, ColumnIndex). The Item word can be omitted because Item is the Range object’s default property. It is necessary to specify the RowIndex argument while ColumnIndex is optional. RowIndex is the index number of the cell, starting with 1 and increasing from left to right and then down. Worksheets(«Sheet1»).Cells.Item(1) or Worksheets(«Sheet1»).Cells(1) refers to range A1 (the top-left cell in the worksheet), Worksheets(«Sheet1»).Cells(2) refers to range B1 (cell next to the right of the top-left cell). While using a single-parameter reference of the Item property (ie. RowIndex), if index exceeds the number of columns in the specified range, the reference will wrap to successive rows within the range columns. Omitting the object qualifier will default to active sheet. Cells(16385) refers to range A2 of the active sheet in Excel 2007 which has 16384 columns, and Cells(16386) refers to range B2, and so on. Also note that RowIndex and ColumnIndex are offsets and relative to the specified Range (ie. relative to the top-left corner of the specified range). Both Range(«B3»).Item(1) and Range(«B3:D6»).Item(1) refer to range B3. The following refer to range D4, the sixth cell in the range: Range(«B3:D6»).Item(6) or Range(«B3:D6»).Cells(6) or Range(«B3:D6»)(6). ColumnIndex refers to the column number of the cell, can be a number starting with 1 or can be a string starting with the letter «A». Worksheets(«Sheet1»).Cells(2, 3) and Worksheets(«Sheet1»).Cells(2, «C») both refer to range C2 wherein the RowIndex is 2 and ColumnIndex is 3 (column C). Range(«C2»).Cells(2, 3) refers to range E3 in the active sheet, and Range(«C2»).Cells(4, 5) refers to range G5 in the active sheet. Using Range(«C2»).Item(2, 3) and Range(«C2»).Item(4, 5) has the same effect and will refer to range E3 & range G5 respectively. Using Range(«C2:D3»).Cells(2, 3) and Range(«C2:D3»).Cells(4, 5) will also refer to range E3 & range G5 respectively. Omitting the Item or Cells word — Range(«C2:D3»)(2, 3) and Range(«C2:D3»)(4, 5) also refers to range E3 & range G5 respectively. It is apparant here that you can refer to and return cells outside the original specified range, using the Item property.

Columns property of the Worksheet object: Use the Worksheet.Columns Property (Syntax: WorksheetObject.Columns) to refer to all columns in a worksheet  which are returned as a Range object. Example: Worksheets(«Sheet1»).Columns will return all columns of the worksheet; Worksheets(«Sheet1»).Columns(1) returns the first column (column A) in the worksheet; Worksheets(«Sheet1»).Columns(«A») returns the first column (column A); Worksheets(«Sheet1»).Columns(«A:C») returns the columns A, B & C; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Columns(1) will return the first column of the active sheet, and will be the same as using Application.Columns(1).

Columns property of the Range object: Use the Range.Columns Property (Syntax: RangeObject.Columns) to refer to columns in a specified range. Example1: color cells from all columns of the specified range ie. B2 to D4: Worksheets(«Sheet1»).Range(«B2:D4»).Columns.Interior.Color = vbYellow. Example2: color cells from first column of the range only ie. B2 to B4: Worksheets(«Sheet1»).Range(«B2:D4»).Columns(1).Interior.Color = vbGreen. If the specified range object contains multiple areas, the columns from the first area only will be returned by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being «B2:D4» and the second area being «F3:G6» — the following code will color cells from first column of the first area only ie. cells B2 to B4: Worksheets(«Sheet1»).Range(«B2:D4, F3:G6»).Columns(1).Interior.Color = vbRed. Omitting the object qualifier will default to active sheet — following will apply color to column A of the ActiveSheet: Columns(1).Interior.Color = vbRed.

Use the Worksheet.Rows Property (Syntax: WorksheetObject.Rows) to refer to all rows in a worksheet  which are returned as a Range object. Example: Worksheets(«Sheet1»).Rows will return all rows of the worksheet; Worksheets(«Sheet1»).Rows(1) returns the first row (row one) in the worksheet; Worksheets(«Sheet1»).Rows(3) returns the third row (row three) in the worksheet; Worksheets(«Sheet1»).Rows(«1:3») returns the first 3 rows; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Rows(1) will return the first row of the active sheet, and will be the same as using Application.Rows(1).

Use the Range.Rows Property (Syntax: RangeObject.Rows) to refer to rows in a specified range. Example1: color cells from all rows of the specified range ie. B2 to D4: Worksheets(«Sheet1»).Range(«B2:D4»).Rows.Interior.Color = vbYellow. Example2: color cells from first row of the range only ie. B2 to D2: Worksheets(«Sheet1»).Range(«B2:D4»).Rows(1).Interior.Color = vbGreen. If the specified range object contains multiple areas, the rows from the first area only will be returned by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being «B2:D4» and the second area being «F3:G6» — the following code will color cells from first row of the first area only ie. cells B2 to D2: Worksheets(«Sheet1»).Range(«B2:D4, F3:G6»).Rows(1).Interior.Color = vbRed. Omitting the object qualifier will default to active sheet — following will apply color to row one of the ActiveSheet: Rows(1).Interior.Color = vbRed.

To refer to a range as offset from a specified range, use the Range.Offset Property. Syntax: RangeObject.Offset(RowOffset, ColumnOffset). Both arguments are optional to specify. The RowOffset argument specifies the number of rows by which the specified range is offset — negative values indicating upward offset and positive values indicating downward offset, with default value being 0. The ColumnOffset argument specifies the number of columns by which the specified range is offset — negative values indicating left offset and positive values indicating right offset, with default value being 0. Examples: Range(«C5»).Offset(1, 2) offsets 1 row & 2 columns and refers to Range E6, Range(«C5:D7»).Offset(1, -2) offsets 1 row downward & 2 columns to the left and refers to Range (A6:B8).

Accessing a worksheet range, with vba code:-

Referencing a single cell:

Enter the value 10 in the cell A1 of the worksheet named «Sheet1» (omitting to mention a property with the Range object will assume the Value property, as shown below):

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

Worksheets(«Sheet1»).Range(«A1») = 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

Example 1 — Using Range, Cells, Columns & Rows property — refer Image 1:

Sub CellsColumnsRowsProperty()
‘using Range, Cells, Columns & Rows property — refer Image 1:

Dim ws As Worksheet
Dim rng As Range
Dim r As Integer, c As Integer, n As Integer, i As Integer, j As Integer

‘set worksheet:
Set ws = Worksheets(«Sheet1»)
‘activate worksheet:
ws.activate

‘enter numbers starting from 1 in each row, for a 5 row & 5 column range (A1:E5):

For r = 1 To 5

n = 1

For c = 1 To 5

Cells(r, c).Value = n

n = n + 1

Next c

Next r

‘set range to A1:E5, wherein the numbers have been entered as above:
Set rng = Range(Cells(1, 1), Cells(5, 5))

‘set background color of each even number column to yellow and of each odd number column to green:

For i = 1 To 5

If i Mod 2 = 0 Then

rng.Columns(i).Interior.Color = vbYellow
Else

rng.Columns(i).Interior.Color = vbGreen

End If

Next i

‘set font color to red and set font to bold for of even number rows:

For j = 1 To 5

If j Mod 2 = 0 Then

rng.Rows(j).Font.Bold = True

rng.Rows(j).Font.Color = vbRed

End If

Next j

‘set font for all cells of the range to italics:
rng.Cells.Font.Italic = True

End Sub

To return the number of the first row in a range, use the Range.Row Property. If the specified range contains multiple areas, this property will return the number of the first row in the first area (Areas property has been explained in detail later in this section). Syntax: RangeObject.Row. To return the number of the first column in a range, use the Range.Column Property. If the specified range contains multiple areas, this property will return the number of the first column in the first area. Syntax: RangeObject.Column.

Examples:

Get the number of the first row in the specified range — returns 4:

MsgBox ActiveSheet.Range(«B4»).Row

MsgBox Worksheets(«Sheet1»).Range(«B4:D7»).Row

Get the number of the first column in the specified range — returns 2:

MsgBox ActiveSheet.Range(«B4:D7»).Column

Get the number of the last row in the specified range — returns 7:

Explanation: Range(«B4:D7»).Rows.Count returns 4 (the number of rows in the range). Range(«B4:D7»).Rows(Range(«B4:D7»).Rows.Count) or Range(«B4:D7»).Rows(4), returns the last row in the specified range.

MsgBox Range(«B4:D7»).Rows(Range(«B4:D7»).

Rows.Count).Row

Example 2: Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows — refer Image 2.

Sub RowColumnProperty()
‘Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows — refer Image 2.

Dim rng As Range, cell As Range
Dim i As Integer

Set rng = Worksheets(«Sheet1»).Range(«B4:D7»)

‘enter its row number & column number within each cell in the specified range:

For Each cell In rng

cell.Value = cell.Row & «,» & cell.Column

Next

‘set background color of each alternate row of the specified range:

For i = 1 To rng.Rows.count

If i Mod 2 = 1 Then

rng.Rows(i).Interior.Color = vbGreen

Else

rng.Rows(i).Interior.Color = vbYellow

End If

Next

End Sub

Also refer to Example 23, of using the End & Row properties to determine the last used row or column with data.

You can get a Range reference in vba language by using the Range.Address Property, which returns the address of a Range as a string value. This property is read-only.

Examples of using the Address Property:

Returns $B$2:

MsgBox Range(«B2»).Address

Returns $B$2,$C$3:

MsgBox Range(«B2,C3»).Address

Returns $A$1:$B$2,$C$3,$D$4:

Dim strRng As String
Range(«A1:B2,C3,D4»).Select
strRng = Selection.Address
MsgBox strRng

Returns $B2:

MsgBox Range(«B2»).Address(RowAbsolute:=False)

Returns B$2:

MsgBox Range(«B2»).Address(ColumnAbsolute:=False)

Returns R2C2:

MsgBox Range(«B2»).Address(ReferenceStyle:=xlR1C1)

Includes the worksheet (active sheet — «Sheet1») & workbook («Book1.xlsm») name, and returns [Book1.xlsm]Sheet1!$B$2:

MsgBox Range(«B2»).Address(External:=True)

Returns R[1]C[-1] — Range(«B2») is 1 row and -1 columns relative to Range(«C1»):

MsgBox Range(«B2»).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlR1C1, RelativeTo:=Range(«C1»))

Returns RC[-2] — Range(«A1») is 0 row and -2 columns relative to Range(«C1»):

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlR1C1, RelativeTo:=Range(«C1»))

Activate & Select Cells; the ActiveCell & Selection

The Select method (of the Range object) is used to select a cell or a range of cells in a worksheet — Syntax: RangeObject.Select. Ensure that the worksheet wherein the Select method is applied to select cells, is the active sheet. The ActiveCell Property (of the Application object) returns a single active cell (Range object) in the active worksheet. Remember that the ActiveCell property will not work if the active sheet is not a worksheet. When a cell(s) is selected in the active window, the Selection property (of the Application object) returns a Range object representing all cells which are currently selected in the active worksheet. A Selection may consist of a single cell or a range of multiple cells, but there will only be one active cell within it, which is returned by using the ActiveCell property. When only a single cell is selected, the ActiveCell property returns this cell. On selecting multiple cells using the Select method, the first referenced cell becomes the active cell, and thereafter you can change the active cell using the Activate method. Both the ActiveCell Property & the Selection property are read-only, and not specifying the Application object qualifier viz. Application.ActiveCell or ActiveCell, Application.Selection or Selection, will have the same effect. To activate a single cell within the current selection, use the Activate Method (of the Range object) — Syntax: RangeObject.Activate, and this activated cell is returned by using the ActiveCell property.

We have discussed above that a Selection may consist of a single cell or a range of multiple cells, whereas there can be only one active cell within the Selection. When you activate a cell outside the current selection, the activated cell becomes the only selected cell. You can also use the Activate method to specify a range of multiple cells, but in effect only a single cell will be activated, and this activated cell will be the top-left corner cell of the range specified in the method. If this top-left cell lies within the selection, the current selection will not change, but if this top-left cell lies outside the selection, then the specified range in the Activate method becomes the new selection.

See below codes which illustrate the concepts of ActiveCell and Selection.

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«C1:F5»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«F5:C1»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«C5:F1»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Activate a cell within the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection remains same — range B6:F10, but the active cell is now C8:
Range(«C8»).Activate
MsgBox ActiveCell.Address

Activate a cell outside the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘both the selection and the active cell is now A2:
Range(«A2»).Activate
MsgBox ActiveCell.Address

Select a cell within the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘both the selection and the active cell is now C8:
Range(«C8»).Select
MsgBox ActiveCell.Address

Activate a range of cells whose top-left cell is within the current selection:

‘selects range B6:F10 — refer Image 3a:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection remains same — range B6:F10, but the active cell is now C8 — refer Image 3b:
Range(«C8:G12»).Activate
MsgBox ActiveCell.Address

Activate a range of cells whose top-left cell is outside the current selection:

‘selects range B6:F10 — refer Image 3a:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection range changes to range B1:F8, and the active cell is now B1 — refer Image 3c:
Range(«B1:F8»).Activate
MsgBox ActiveCell.Address

Using the Application.Selection Property returns the selected object wherein the selection determines the returned object type. Where the selection is a range of cells, this property returns a Range object, and this Selection — which is a Range object — can comprise of a single cell, or multiple cells or multiple non-contiguous ranges. And as mentioned above, the Select method (of the Range object) is used to select a cell or a range of cells in a worksheet. Therefore, after selecting a range, you can perform actions on the selection of cells by using the Selection object. See below illustration. 

Sub SelectionObject()

‘select cells in the active sheet using the Range.Select method:

Range(«A1:B3,D6»).Select

‘perform action (set interior color of cells to red) on the Selection, which is a Range object:

Selection.Interior.Color = vbRed

End Sub

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method

Use the Range.EntireRow Property to return an entire row or rows within which the specific range is contained. Using this property returns a Range object referring to the entire row(s). Syntax: RangeObject.EntireRow. Use the Range.EntireColumn Property to return an entire column or columns within which the specific range is contained. Using this property returns a Range object referring to the entire column(s). Syntax: RangeObject.EntireColumn.

Examples of using the EntireRow & EntireColumn Properties

Selects row no. 2:

Range(«A2»).EntireRow.Select

Selects row nos. 2, 3 & 4:

Range(«A2:C4»).EntireRow.Select

Enters value 3 in range A3 ie. in the first cell of row no. 3:

Cells(3, 4).EntireRow.Cells(1, 1).Value = 3

Selects column A:

Range(«A2»).EntireColumn.Select

Selects columns A to C:

Range(«A2:C4»).EntireColumn.Select

Enters value 4 in range D1 ie. in the first cell of column no. 4:

Cells(3, 4).EntireColumn.Cells(1, 1).Value = 4

Use the Range.Insert Method to insert a cell or a range of cells in a worksheet. Syntax: RangeObject.Insert(Shift, CopyOrigin). Both arguments are optional to specify. When you insert cell(s) the other cells are shifted to make way, and you can set a value for the Shift argument to determine the direction in which the other cells are shifted — specifying xlShiftDown (value -4121) will shift the cells down, and xlShiftToRight (value -4161) shifts the cells to the right. Omitting this argument will decide the shift direction based on the shape of the range. Specifying xlFormatFromLeftOrAbove (value 0) for the CopyOrigin argument will copy the format for inserted cell(s) from the above cells or cells to the left, and specifying xlFormatFromRightOrBelow (value 1) will copy format from the below cells or cells to the right.

Illustrating Range.Insert Method — for start data refer Image 4a:

Shifts cells down and copies formatting of inserted cell from above cell — refer image 4b:

Range(«B2»).Insert

Shifts cells to the right and copies formatting of inserted cells from cells to the left — refer image 4c:

Range(«B2:C4»).Insert

Shifts cells down and copies formatting of inserted cells from above cells — refer image 4d:

Range(«B2:D3»).Insert

Shifts cells down and copies formatting of inserted cells from below cells — refer image 4e:

Range(«B2:D3»).Insert CopyOrigin:=xlFormatFromRightOrBelow

Shifts cells to the right and copies formatting of inserted cells from cells to the left — refer image 4f:

Range(«B2:D3»).Insert shift:=xlShiftToRight

Shifts cells to the right and copies formatting of inserted cells from cells to the right — refer image 4g:

Range(«B2:D3»).Insert shift:=xlShiftToRight, CopyOrigin:=xlFormatFromRightOrBelow

Inserts 2 rows — row no 2 & 3 — and copies formatting of inserted rows from above cells — refer image 4h:

Range(«B2:D3»).EntireRow.Insert

Below are some illustrations of inserting entire row(s) or column(s) dynamically in a worksheet.

Example 3: Insert row or column — specify the row / column to insert.

Sub InsertRowColumn()
‘Insert row or column — specify the row / column to insert:

Dim ws As Worksheet
Set ws = Worksheets(«Sheet1»)

‘NOTE: each of the below codes need to be run individually.

‘specify the exact row number to insert — insert a row as row no 12:
ws.Rows(12).Insert

‘specify the range below which to insert a row — insert a row below range C3 ie. as row no 4.
ws.Range(«C3»).EntireRow.Offset(1, 0).Insert

‘specify the exact column number to insert — insert a column as column no 4:
ws.Columns(4).Insert

‘specify the range to the right of which to insert a column — insert a column to the right of range C3 ie. as column no 4.

ws.Range(«C3»).EntireColumn.Offset(0, 1).Insert

End Sub

Example 4: Insert row(s) after a specified value is found.

Sub InsertRow1()
‘insert row(s) after a specified value is found:

Dim ws As Worksheet
Dim rngFind As Range, rngSearch As Range, rngLastCell As Range
Dim lFindRow As Long

Set ws = Worksheets(«Sheet1»)

‘find a value after which to insert a row:
Set rngSearch = ws.Range(«A1:E100»)
‘begin search AFTER the last cell in search range (this will start serach from the first cell in search range):
Set rngLastCell = rngSearch.Cells(rngSearch.Cells.count)
Set rngFind = rngSearch.Find(What:=«ExcelVBA», After:=rngLastCell, LookIn:=xlValues, lookat:=xlWhole)

‘exit procedure if value not found:

If Not rngFind Is Nothing Then

lFindRow = rngFind.Row

MsgBox lFindRow

Else

MsgBox «Value not found!»

Exit Sub

End If

‘NOTE: each of the below codes need to be run individually.

‘if value found is in row no 12, one row will be inserted below as row no 13:
ws.Cells(lFindRow + 1, 1).EntireRow.Insert

‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15):
ws.Cells(lFindRow + 3, 1).EntireRow.Insert

‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15):
ws.Cells(lFindRow, 1).Offset(3).EntireRow.Insert

‘if value found is in row no 12, 3 rows will be inserted above (as row nos 12, 13 & 14) and the value found row 12 will be pushed down to row 15:
ws.Cells(lFindRow, 1).EntireRow.Resize(3).Insert
‘alternate:
ws.Range(Cells(lFindRow, 1), Cells(lFindRow + 2, 1)).EntireRow.Insert
‘alternate:
ws.Rows(lFindRow & «:» & lFindRow + 2).EntireRow.Insert Shift:=xlDown

‘if value found is in row no 12, 3 rows will be inserted below (as row nos 13, 14 & 15) and the value found row 12 will remain at the same position:
ws.Cells(lFindRow + 1, 1).EntireRow.Resize(3).Insert
‘alternate:
ws.Range(ws.Cells(lFindRow + 1, 1), ws.Cells(lFindRow + 3, 1)).EntireRow.Insert

‘if value found is in row no 12, 3 rows will be inserted after row no 13 (as row nos 14, 15 & 16) and existing rows 12 & 13 will remain at the same position:

ws.Cells(lFindRow + 2, 1).EntireRow.Resize(3).Insert

End Sub

Example 5: Insert a row, n rows above the last used row.

Sub InsertRow2()
‘insert a row, n rows above the last used row

Dim ws As Worksheet
Dim lRowsC As Long

Set ws = Worksheets(«Sheet1»)

‘determine the last used row in a column (column A):
lRowsC = ws.Cells(Rows.count, «A»).End(xlUp).Row
MsgBox lRowsC

‘set n to the no of rows above the last used row:
n = 5

‘check if there are enough rows before the last used row, else you will get an error:

If lRowsC >= n Then

‘insert a row, n rows above the last used row — if last used row is no 5 before insertion, then insert as row no 1 and the last used row will become no 6 (similarly, if last used row is 27, then insert as row no 23) :

ws.Rows(lRowsC).Offset(-n + 1, 0).EntireRow.Insert

Else

MsgBox «Not enough rows before the last used row!»

End If

End Sub

Example 6: Insert a row each time the searched value is found in a range.

For live code of this example, click to download excel file.

Sub InsertRow3()
‘search value in a range and insert a row each time the value is found.
‘you can set the search range with the variable rngSearch in below code — the code will look within this range to find the value below which row is to be inserted.

Dim ws As Worksheet
Dim rngFind As Range, rngSearch As Range, rngLastCell As Range
Dim strAddress As String

Set ws = Worksheets(«Sheet1»)

‘set search range:
Set rngSearch = ws.Range(«A1:K100»)
MsgBox «Searching for ‘ExcelVBA’ within range: » & rngSearch.Address
‘begin search AFTER the last cell in search range
Set rngLastCell = rngSearch.Cells(rngSearch.Cells.count)

‘find value in specified range, starting search AFTER the last cell in search range:
Set rngFind = rngSearch.Find(What:=«ExcelVBA», After:=rngLastCell, LookIn:=xlValues, lookat:=xlWhole)

If rngFind Is Nothing Then

MsgBox «Value not found!»

Exit Sub

Else

‘save cell address of first value found:

strAddress = rngFind.Address

Do

‘find next occurrence of value:

Set rngFind = rngSearch.FindNext(After:=rngFind)

‘insert row below when value is found (if value is found twice in a row, then 2 rows will be inserted):

rngFind.Offset(1).EntireRow.Insert

‘loop till reaching the first value found range:

Loop While rngFind.Address <> strAddress

End If

End Sub

Example 7: Insert rows (user-defined number) within consecutive values found in a column — refer Images 5a & 5b.

For live code of this example, click to download excel file.

Sub InsertRow4()
‘insert rows (user-defined number) wherever 2 consecutive values are found in a column.
‘set column number in which 2 consecutive values are checked to insert rows, using the variable lCellColumn in below code.
‘set row number from where to start searching consecutive values, using the variable lCellRow in below code.
‘refer Image 5a which shows raw data, and Image 5b after this procedure is executed — a single row (lRowsInsert value entered as 1 in input box) is inserted where consecutive values appear in column 1:

Dim ws As Worksheet
Dim lLastUsedRow As Long, lRowsInsert As Long, lCellRow As Long, lCellColumn As Long
Dim rng As Range

Set ws = Worksheets(«Sheet1»)
ws.Activate

‘set column number in which 2 consecutive values are checked to insert rows:
lCellColumn = 1
‘set row number from where to start searching consecutive values:
lCellRow = 1

‘determine the last used row in the column (column no. lCellColumn):
lLastUsedRow = Cells(Rows.count, lCellColumn).End(xlUp).Row

‘enter number of rows to insert between 2 consecutive values:
lRowsInsert = InputBox(«Enter number of rows to insert»)

If lRowsInsert < 1 Then

MsgBox «Error — please enter a value equal to or greater than 1»

Exit Sub

End If

MsgBox «This code will insert » & lRowsInsert & » rows, wherever consecutive values are found in column number » & lCellColumn & «, starting search from row number » & lCellRow

‘loop till the row number equals the last used row (ie. loop right till the end value in the column):

Do While lCellRow < lLastUsedRow

Set rng = Cells(lCellRow, lCellColumn)

‘in case of 2 consecutive values:

If rng <> «» And rng.Offset(1, 0) <> «» Then

‘enter the user-defined number of rows:

Range(rng.Offset(1, 0), rng.Offset(lRowsInsert, 0)).EntireRow.Insert

lCellRow = lCellRow + lRowsInsert + 1

‘determine the last used row — it is dynamic and changes on insertion of rows:

lLastUsedRow = Cells(Rows.count, lCellColumn).End(xlUp).Row

‘alternate method to determine the last used row, when number of rows inserted is fixed — this is faster than using End(xlUp):

‘lLastUsedRow = lLastUsedRow + lRowsInsert + 1

‘MsgBox lLastUsedRow

Else

lCellRow = lCellRow + 1

End If

Loop

End Sub

Named ranges are one of these crusty old features in Excel that few users understand. New users may find them weird and scary, and even old hands may avoid them because they seem pointless and complex.

But named ranges are actually a pretty cool feature. They can make formulas *a lot* easier to create, read, and maintain. And as a bonus, they make formulas easier to reuse (more portable).

In fact, I use named ranges all the time when testing and prototyping formulas. They help me get formulas working faster. I also use named ranges because I’m lazy, and don’t like typing in complex references :)

The basics of named ranges in Excel

What is a named range?

A named range is just a human-readable name for a range of cells in Excel. For example, if I name the range A1:A100 «data», I can use MAX to get the maximum value with a simple formula:

 =MAX(data) // max value

Simple named range called "data"

The beauty of named ranges is that you can use meaningful names in your formulas without thinking about cell references. Once you have a named range, just use it just like a cell reference. All of these formulas are valid with the named range «data»:

=MAX(data) // max value
=MIN(data) // min value
=COUNT(data) // total values
=AVERAGE(data) // min value

Video: How to create a named range

Creating a named range is easy

Creating a named range is fast and easy. Just select a range of cells, and type a name into the name box. When you press return, the name is created:

Create a named range fast with name box

To quickly test the new range, choose the new name in the dropdown next to the name box. Excel will select the range on the worksheet.

Excel can create names automatically (ctrl + shift + F3)

If you have well structured data with labels, you can have Excel create named ranges for you. Just select the data, along with the labels, and use the «Create from Selection» command on the Formulas tab of the ribbon:

Create names from selection command on ribbon

You can also use the keyboard shortcut control + shift + F3.

Using this feature, we can create named ranges for the population of 12 states in one step:

Create names from selection with data and labels selected

When you click OK, the names are created. You’ll find all newly created names in the drop down menu next to the name box:

New names also appear in the name box drop down menu

With names created, you can use them in formulas like this

=SUM(MN,WI,MI)

Update named ranges in the Name Manager (Control + F3)

Once you create a named range, use the Name Manager (Control + F3) to update as needed. Select the name you want to work with, then change the reference directly (i.e. edit «refers to»), or click the button at right and select a new range.

Updated named ranges with the Name Manager

There’s no need to click the Edit button to update a reference. When you click Close, the range name will be updated.

Note: if you select an entire named range on a worksheet, you can drag to a new location and the reference will be updated automatically. However, I don’t know a way to adjust range references by clicking and dragging directly on the worksheet. If you know a way to do this, chime in below!

See all named ranges (control + F3)

To quickly see all named ranges in a workbook, use the dropdown menu next to the name box.

If you want to see more detail, open the Name Manager (Control + F3), which lists all names with references, and provides a filter as well:

The name manager shows all newly created names

Note: in older versions of Excel on the Mac, there is no Name Manager, and you’ll see the Define Name dialog instead.

Copy and paste all named ranges (F3)

If you want a more persistent record of named ranges in a workbook, you can paste the full list of names anywhere you like. Go to Formulas > Use in Formula (or use the shortcut F3), then choose Paste names > Paste List:

Paste names dialog box

When you click the Paste List button, you’ll see the names and references pasted into the worksheet:

After pasting named ranges into worksheet

See names directly on the worksheet

If you set the zoom level to less than 40%, Excel will show range names directly on the worksheet:

At zoom level <40%, Excel will show range names

Thanks for this tip, Felipe!

Names have rules

When creating named ranges, follow these rules:

  1. Names must begin with a letter, an underscore (_), or a backslash ()
  2. Names can’t contain spaces and most punctuation characters.
  3. Names can’t conflict with cell references – you can’t name a range «A1» or «Z100».
  4. Single letters are OK for names («a», «b», «x», etc.), but the letters «r» and «c» are reserved.
  5. Names are not case-sensitive – «home», «HOME», and «HoMe» are all the same to Excel.

Named ranges in formulas

Named ranges are easy to use in formulas

For example, lets say you name a cell in your workbook «updated». The idea is you can put the current date in the cell (Ctrl + ;) and refer to the date elsewhere in the workbook.

Using a named range inside a text formula

The formula in B8 looks like this:

="Updated: "& TEXT(updated, "ddd, mmmm d, yyyy")

You can paste this formula anywhere in the workbook and it will display correctly. Whenever you change the date in «updated», the message will update wherever the formula is used. See this page for more examples.

Named ranges appear when typing a formula

Once you’ve created a named range, it will appear automatically in formulas when you type the first letter of the name. Press the tab key to enter the name when you have a match and want Excel to enter the name.

Named ranges appear when entering formulas

Named ranges can work like constants

Because named ranges are created in a central location, you can use them like constants without a cell reference. For example, you can create names like «MPG» (miles per gallon) and «CPG» (cost per gallon) with and assign fixed values:

Named ranges can work like constants, with no cell reference

Then you can use these names anywhere you like in formulas, and update their value in one central location.

Using a named range like a constant in a formula

Named ranges are absolute by default

By default, named ranges behave like absolute references. For example, in this worksheet, the formula to calculate fuel would be:

=C5/$D$2

Standard formula with absolute address

The reference to D2 is absolute (locked) so the formula can be copied down without D2 changing.

If we name D2 «MPG» the formula becomes:

=C5/MPG

Using a named range like a constant in a formula

Since MPG is absolute by default, the formula can be copied down column D as-is.

Named ranges can also be relative

Although named ranges are absolute by default, they can also be relative.  A relative named range refers to a range that is relative to the position of the active cell at the time the range is created. As a result, relative named ranges are useful building generic formulas that work wherever they are moved.

For example, you can create a generic «CellAbove» named range like this:

  1. Select cell A2
  2. Control + F3 to open Name Manager
  3. Tab into ‘Refers to’ section, then type: =A1

CellAbove will now retrieve the value from the cell above wherever it is it used.

Important: make sure the active cell is at the correct location before creating the name.

Apply named ranges to existing formulas

If you have existing formulas that don’t use named ranges, you can ask Excel to apply the named ranges in the formulas for you. Start by selecting the cells that contain formulas you want to update. Then run Formulas > Define Names > Apply Names.

The Apply Names dialog box

Excel will then replace references that have a corresponding named range with the name itself.

You can also apply names with find and replace:

Applying names ranges with find and replace

Important: Save a backup of your worksheet, and select just the cells you want to change before using find and replace on formulas.

Key benefits of named ranges

Named ranges make formulas easier to read

The biggest single benefit to named ranges is they make formulas easier to read and maintain. This is because they replace cryptic references with meaningful names. For example, consider this worksheet with data on planets in our solar system.  Without named ranges, a VLOOKUP formula to fetch «Position» from the table is quite cryptic:

=VLOOKUP($H$4,$B$3:$E$11,2,0)

Without named ranges formulas can be cryptic

However, with B3:E11 named «data», and H4 named «planet», we can write formulas like this:

=VLOOKUP(planet,data,2,0) // position
=VLOOKUP(planet,data,3,0) // diameter
=VLOOKUP(planet,data,4,0) // satellites

With named ranges, formulas can be simple

At a glance, you can see the only difference in these formulas in the column index.

Named ranges make formulas portable and reusable

Named ranges can make it much easier to reuse a formula in a different worksheet. If you define names ahead of time in a worksheet, you can paste in a formula that uses these names and it will «just work». This is a great way to quickly get a formula working.

For example, this formula counts unique values in a range of numeric data:

=SUM(--(FREQUENCY(data,data)>0))

To quickly «port» this formula to your own worksheet, name a range «data» and paste the formula into the worksheet. As long as «data» contains numeric values, the formula will work straightway.

Tip: I recommend that you create the needed range names *first* in the destination workbook, then copy in the formula as text only (i.e. don’t copy the cell that contains the formula in another worksheet, just copy the text of the formula). This stops Excel from creating names on-the-fly and lets you to fully control the name creation process. To copy only formula text, copy text from the formula bar, or copy via another application (i.e. browser, text editor, etc.).

Named ranges can be used for navigation

Named ranges are great for quick navigation. Just select the dropdown menu next to the name box, and choose a name. When you release the mouse, the range will be selected. When a named range exists on another sheet, you’ll be taken to that sheet automatically.

Named ranges allow for simple navigation

Named ranges work well with hyperlinks

Named ranges make hyperlinks easy. For example, if you name A1 in Sheet1 «home», you can create a hyperlink somewhere else that takes you back there.

Creating a hyperlink to a named range

Example of named range hyperlink on the worksheet

To use a named range inside the HYPERLINK function, add a hash (#) in front of the named range:

=HYPERLINK("#home","take me home")

You can use this same syntax to create a hyperlink to a table:

=HYPERLINK("#Table1","Go to Table1")

Note: in older versions of Excel you can’t link to a table like this. However, you can define a name equal to a table (i.e. =Table1) and hyperlink to that.

Named ranges for data validation

Names ranges work well for data validation, since they let you use a logically named reference to validate input with a drop down menu. Below, the range G4:G8 is named «statuslist», then apply data validation with a List linked like this:

Using a named range for data validation with list

The result is a dropdown menu in column E that only allows values in the named range:

Data validation with named range example

Dynamic Named Ranges

Names ranges are extremely useful when they automatically adjust to new data in a worksheet. A range set up this way is referred to as a «dynamic named range». There are two ways to make a range dynamic: formulas and tables.

Dynamic named range with a Table

A Table is the easiest way to create a dynamic named range. Select any cell in the data, then use the shortcut Control + T:

Creating am Excel Table

When you create an Excel Table, a name is automatically created (e.g. Table1), but you can rename the table as you like. Once you have created a table, it will expand automatically when data is added.

Tables will expand automatically and can be renamed

Dynamic named range with a formula

You can also create a dynamic named range with formulas, using functions like OFFSET and INDEX. Although these formulas are moderately complex, they provide a lightweight solution when you don’t want to use a table. The links below provide examples with full explanations:

  • Example of dynamic range formula with INDEX
  • Example of dynamic range formula with OFFSET

Table names in data validation

Since Excel Tables provide an automatic dynamic range, they would seem to be a natural fit for data validation rules, where the goal is to validate against a list that may be always changing. However, one problem with tables is that you can’t use structured references directly to create data validation or conditional formatting rules. In other words, you can’t use a table name in conditional formatting or data validation input areas.

However, as a workaround, you can define named a named range that points to a table, and then use the named range for data validation or conditional formatting. The video below runs through this approach in detail.

Video: How to use named ranges with tables

Deleting named ranges

Note: If you have formulas that refer to named ranges, you may want to update the formulas first before removing names. Otherwise, you’ll see #NAME? errors in formulas that still refer to deleted names. Always save your worksheet before removing named ranges in case you have problems and need to revert to the original.

Named ranges adjust when deleting and inserting cells 

When you delete *part* of a named range, or if  insert cells/rows/columns inside a named range, the range reference will adjust accordingly and remain valid. However, if you delete all of the cells that enclose a named range, the named range will lose the reference and display a #REF error. For example, if I name A1 «test», then delete column A, the name manager will show «refers to» as:

=Sheet1!#REF!

Delete names with Name Manager

To remove named ranges from a workbook manually, open the name manager, select a range, and click the Delete button. If you want to remove more than one name at the same time, you can Shift + Click or Ctrl + Click to select multiple names, then delete in one step.

Delete names with errors

If you have a lot of names with reference errors, you can use the filter button in the name manager to filter on names with errors:

Name Manager filter menu

Then shift+click to select all names and delete.

Named ranges and Scope

Named ranges in Excel have something called «scope», which determines whether a named range is local to a given worksheet, or global across the entire workbook. Global names have a scope of «workbook», and local names have a scope equal to the sheet name they exist on. For example, the scope for a local name might be «Sheet2». 

The purpose of scope

Named ranges with a global scope are useful when you want all sheets in a workbook to have access to certain data, variables, or constants. For example, you might use a global named range a tax rate assumption used in several worksheets.

Local scope

Local scope means a name is works only on the sheet it was created on. This means you can have multiple worksheets in the same workbook that all use the same name. For example, perhaps you have a workbook with monthly tracking sheets (one per month) that use named ranges with the same name, all scoped locally. This might allow you to reuse the same formulas in different sheets. The local scope allows the names in each sheet to work correctly without colliding with names in the other sheets.

To refer to a name with a local scope, you can prefix the sheet name to the range name:

Sheet1!total_revenue
Sheet2!total_revenue
Sheet3!total_revenue

Range names created with the name box automatically have global scope. To override this behavior, add the sheet name when defining the name:

Sheet3!my_new_name

Global scope

Global scope means a name will work anywhere in a workbook. For example, you could name a cell «last_update», enter a date in the cell. Then you can use the formula below to display the date last updated in any worksheet.

=last_update

Global names must be unique within a workbook.

Local scope

Locally scoped named ranges make sense for worksheets that use named ranges for local assumptions only. For example, perhaps you have a workbook with monthly tracking sheets (one per month) that use named ranges with the same name, all scoped locally. The local scope allows the names in each sheet to work correctly without colliding with names in the other sheets.

Managing named range scope

By default, new names created with the namebox are global, and you can’t edit the scope of a named range after it’s created. However, as a workaround, you can delete and recreate a name with the desired scope.

If you want to change several names at once from global to local, sometimes it makes sense to copy the sheet that contains the names. When you duplicate a worksheet that contains named ranges, Excel copies the named ranges to the second sheet, changing the scope to local at the same time. After you have the second sheet with locally scoped names, you can optionally delete the first sheet.

Jan Karel Pieterse and Charles Williams have developed a utility called the Name Manager that provides many useful operations for named ranges. You can download the Name Manager utility here.

In this guide, we’re going to show you how to refer a range or a cell in Excel VBA.

VBA Basics

Before diving into the code, let’s start with a cell or a range means in VBA. First, VBA is an object-based programming language, which means that the language refers each element as objects. Objects have properties that define them, and they can encapsulate other objects, or codes. Thus, a single cell, a range of cells, a worksheet, or Excel software as a whole is an object for VBA. You can think this as a hierarchical model.

The image illustrates only a small portion of Excel objects in VBA. An Excel instance contains a Workbooks collection. A collection is a group of related objects. For example, if you open two workbooks, the Workbooks collection has two Workbook object. Each Workbook object has its own worksheets under a Worksheets collection. This structure applies to all.

VBA envelops all cell and cell-based references in an object called Range. In theory, when a particular object is referenced, you also need to specify its parents. In VBA syntax, a dot (.) operator is used to move through object hierarchy. For example, to access the Range object, the code should be:

Application.Workbooks.Worksheets.Range

However, this reference is ambiguous when it comes to specify which Excel workbook or worksheet you are referring to. In order to do this, you must supply the name or the index number (starting with 1) of the particular object you are referring. This approach is like in Excel formulas — the argument is given in parentheses. For example to refer the range object in the worksheet “Sheet1” of the workbook “Book1.xlsm”:

Application.Workbooks("Book1.xlsm").Worksheets("Sheet1").Range

or

Application.Workbooks(1).Worksheets(1).Range

You do not have to specify all parents for Range object every time. If your intention is to work on the active sheet of the active workbook, you can simply use Range.

Range Object

The Range object allows you to refer a cell or cells just like in any Excel formula. For example,

Range("A1") 'Refers the cell A1
Range("A2:D11") 'Refers the range of cells between A2:D11
Range("A3,B4:E6,F12") 'Refers all cells in the cells A3, F12 and the range B4:E6
Range("2:2") 'Entire 2nd row
Range("E:E") 'Entire column E
Range("Input") 'Named range "Input"

Using square brackets to refer a range or a cell

You can use square brackets ([]) instead of the “Range” keyword and double quotes (“). This approach as essentially a shortcut, and the outcome is the same.

[A1] 'Refers the cell A1
[A2:D11] 'Refers the range of cells between A2:D11
[A3,B4:E6,F12] 'Refers all cells in the cells A3, F12 and the range B4:E6
[2:2] 'Entire 2nd row
[E:E] 'Entire column E
[Input] 'Named range "Input"

Cells property to refer a range or a cell

Cells is the name of a property of both Worksheet and Range objects. It is neither a collection nor an object. Thus, there are no objects named Cell.

In other words, the Cells property returns a Range object as well. Each Cells property in Worksheet and Range objects work in its parent’s context only. This behavior might make more sense within examples.

Syntax

The Cells property can be used in two ways:
With row and column index numbers:

Cells(row number,column number) 

With index number of the cell:

Cells(cell number) ‘refers the 23rd cell in the range

Examples

Worksheet.Cells

Cells property of a Worksheet object returns the cell in a specific location in the worksheet.
With row and column index numbers:

Cells(3,2) 'refers the cell at third row and second column in the active sheet (B3)

How to refer a range or a cell in Excel VBA 02
With index number of the cell:

Cells(5) 'refers the 5th cell in the range (E1)

The numbering of cells starts from 1, and increases from left to right and from top to bottom. This means that A1 is the first cell.

Range.Cells

On the other hand, the Cells property of a Range object returns the cell in specified location in the range.
With row and column index numbers:

Range(&quot;C4:F9&quot;).Cells(3,2) 'refers the cell at third row and second column in the active range (D6)


With index number of the cell:

Range(&quot;C4:F9&quot;).Cells(5) ‘refers the 5th cell in the range (C5)

Active objects to refer a range or a cell

There are keywords in VBA to reference active(selected) objects when the code is running.

ActiveCell 'Refers the selected cell
Selection 'Refers any selected object. This can be cells or a chart
ActiveSheet 'Refers the active worksheet
ActiveWorkbook 'Refers the active worksheet

Понравилась статья? Поделить с друзьями:
  • Regex word space word
  • Refers to another word
  • Regex word or digit
  • Referential meaning of the word
  • Regex word not number