Vba excel формулы r1c1

Вставка формулы со ссылками в стиле A1 и R1C1 в ячейку (диапазон) из кода VBA Excel. Свойства Range.FormulaLocal и Range.FormulaR1C1Local.

Свойство Range.FormulaLocal

FormulaLocal — это свойство объекта Range, которое возвращает или задает формулу на языке пользователя, используя ссылки в стиле A1.

В качестве примера будем использовать диапазон A1:E10, заполненный числами, которые необходимо сложить построчно и результат отобразить в столбце F:

Примеры вставки формул суммирования в ячейку F1:

Range(«F1»).FormulaLocal = «=СУММ(A1:E1)»

Range(«F1»).FormulaLocal = «=СУММ(A1;B1;C1;D1;E1)»

Пример вставки формул суммирования со ссылками в стиле A1 в диапазон F1:F10:

Sub Primer1()

Dim i As Byte

    For i = 1 To 10

        Range(«F» & i).FormulaLocal = «=СУММ(A» & i & «:E» & i & «)»

    Next

End Sub

В этой статье я не рассматриваю свойство Range.Formula, но если вы решите его применить для вставки формулы в ячейку, используйте англоязычные функции, а в качестве разделителей аргументов — запятые (,) вместо точек с запятой (;):

Range(«F1»).Formula = «=SUM(A1,B1,C1,D1,E1)»

После вставки формула автоматически преобразуется в локальную (на языке пользователя).

Свойство Range.FormulaR1C1Local

FormulaR1C1Local — это свойство объекта Range, которое возвращает или задает формулу на языке пользователя, используя ссылки в стиле R1C1.

Формулы со ссылками в стиле R1C1 можно вставлять в ячейки рабочей книги Excel, в которой по умолчанию установлены ссылки в стиле A1. Вставленные ссылки в стиле R1C1 будут автоматически преобразованы в ссылки в стиле A1.

Примеры вставки формул суммирования со ссылками в стиле R1C1 в ячейку F1 (для той же таблицы):

‘Абсолютные ссылки в стиле R1C1:

Range(«F1»).FormulaR1C1Local = «=СУММ(R1C1:R1C5)»

Range(«F1»).FormulaR1C1Local = «=СУММ(R1C1;R1C2;R1C3;R1C4;R1C5)»

‘Ссылки в стиле R1C1, абсолютные по столбцам и относительные по строкам:

Range(«F1»).FormulaR1C1Local = «=СУММ(RC1:RC5)»

Range(«F1»).FormulaR1C1Local = «=СУММ(RC1;RC2;RC3;RC4;RC5)»

‘Относительные ссылки в стиле R1C1:

Range(«F1»).FormulaR1C1Local = «=СУММ(RC[-5]:RC[-1])»

Range(«F2»).FormulaR1C1Local = «=СУММ(RC[-5];RC[-4];RC[-3];RC[-2];RC[-1])»

Пример вставки формул суммирования со ссылками в стиле R1C1 в диапазон F1:F10:

‘Ссылки в стиле R1C1, абсолютные по столбцам и относительные по строкам:

Range(«F1:F10»).FormulaR1C1Local = «=СУММ(RC1:RC5)»

‘Относительные ссылки в стиле R1C1:

Range(«F1:F10»).FormulaR1C1Local = «=СУММ(RC[-5]:RC[-1])»

Так как формулы с относительными ссылками и относительными по строкам ссылками в стиле R1C1 для всех ячеек столбца F одинаковы, их можно вставить сразу, без использования цикла, во весь диапазон.


Excel VBA Tutorial about the R1C1-style notation and FormulaR1C1If you’ve used the macro recorder, you’re probably familiar with both R1C1-style notation and the FormulaR1C1 property. This is because, as explained at Stack Overflow, the macro recorder constantly uses FormulaR1C1.

For example, even though you normally use the Range.Value property for purposes of entering a value in a cell, the macro recorder uses the Range.FormulaR1C1 property for those same purposes. To give you an idea, I used the macro recorder for purposes of creating the following sample macro (Enter_Value_FormulaR1C1). I recorded my actions while (i) entering numbers 1 through 5 in cells B5 to B9 and (ii) selecting cell B10 at the end.

Excel table with data used for Macro Recorder

Notice how the macro recorder uses the FormulaR1C1 property every single time.

VBA code from Macro Recorder with FormulaR1C1 property

As explained in Excel 2016 Power Programming with VBA and by Bob Phillips at excelforum.com, you normally use the Range.Value property for purposes of entering a value in a cell. In practice, using FormulaR1C1 “produces the same result”.

However, my focus on this particular VBA tutorial isn’t comparing the Range.FormulaR1C1 property with the Range.Value property. My focus is the Range.FormulaR1C1 property itself and the R1C1-style notation.

More particularly, my purpose with this blog post is to provide you with all the information you need to understand and use both the R1C1-style notation and the Range.FormulaR1C1 property.

You might be wondering whether you should take the time to learn about these 2 topics.

If that’s the case, you can refer to the section below where I explain why R1C1-style references and the Range.FormulaR1C1 property are useful. For the moment, and to make it short, my opinion is that you should take the time to learn and understand both the R1C1-style notation and the FormulaR1C1 property because, as explained by Excel authorities Bill Jelen (Mr. Excel) and Tracy Syrstad in Excel 2016 VBA and Macros:

Taking 30 minutes to understand R1C1 will make every macro you write for the rest of your life easier to code.

The following table of contents lists the main sections of this Excel tutorial:

Now, let’s start by taking a look at…

R1C1-Style And A1-Style Notation: A Basic Introduction

In order to understand the rest of this Excel tutorial, and how the FormulaR1C1 property may help you when working with VBA, having a good understanding of R1C1 notation is useful. I provide an introduction to the R1C1 notation in this section.

First, let me explain what I mean by “notation”:

When working with Excel formulas, notation is (in broad terms) the system you use to represent a cell reference. When referring to a cell in Excel, you usually create the reference by taking into consideration the following 2 items:

  • Column.
  • Row.

If you’ve been working with Excel for a while, you’re probably quite familiar with the most common notation:

A1-Style Notation

The A1 reference style is Excel’s default style notation.

As explained by Microsoft, when you build a cell reference using the A1 reference style, you:

  • Refer to the column by using the letter that appears in the column heading. In recent Excel versions, this letter can be from A to XFD.

    Column headings with A1-style notation

  • Refer to the row by using the number that appears in the row heading. In recent Excel versions, this number ranges from 1 to 1,048,576.

    Excel row headings with numbers

When using the A1-style notation, you create a cell reference by concatenating the column letter and the row number. For example:

  • “A1” refers to the first cell in the worksheet, where column A and row 1 intersect.

    A1 cell in Excel

  • “C5” refers to the cell at the intersection of column C and row 5.

    E5 cell in Excel

  • “E10” makes reference to the cell where column E and row 10 intersect.

    Cell E10 in Excel

  • And so on. You probably get the idea.

In other words, A1-style notation is simply the cell reference style you’re used to working with in Excel.

With this basic knowledge of what notation and the A1-style notation are, we can take a closer look at:

R1C1-Style Notation

R1C1-style notation is the alternative reference style to the A1-style notation I explain in the previous section.

The main difference between the A1 and R1C1 notations is the way in which columns are identified. Here’s what I mean:

  • When you’re using the A1-style notation, columns are identified by letters. I explain this in the previous section.
  • When you’re working with R1C1-style references, columns are identified by numbers. In recent Excel versions, this number can be from 1 to 16,384.

    Column headings in R1C1-style notation

What’s the bottom line?

Well, as explained by Microsoft, in the R1C1-style notation:

Both the rows and the columns on the worksheet are numbered.

A second, also important, difference between the A1 and R1C1 styles is the way in which you identify rows and columns when building cell references. As I mention above, when you’re working with the A1 system, you create a reference by concatenating (i) the column identifier and (ii) the row identifier.

When you’re working the R1C1-style references, 2 things change:

  • #1: The order in which you concatenate the rows and columns. Therefore:

    If you’re working with A1-style references, (i) the column goes first and (ii) the row goes second.

    If you’re using the R1C1 style, you concatenate the rows and columns in the opposite order. That is: (i) the row goes first and (ii) the column goes second.

  • #2: The way in which you identify the relevant rows and columns. What I mean is the following:

    If you’re using the A1 style, you concatenate the column letter and the row number. This is what I explain in the previous section.

    If you’re working with the R1C1-style notation: (i) the column number is preceded by the letter “C” and (ii) the row number is preceded by the letter “R”.

Let’s see how this looks like in practice:

  • “R1C1” refers to the cell at the intersection of the first column and the first row. In A1-style notation (as I explain above) you refer to this cell as A1.

    R1C1 cell in Excel

  • “R5C3” makes reference to the cell where the fifth row and the third column intersect. In the example that I provide in the previous section (using the A1 style), you call this cell C5.

    R5C3 cell in Excel

  • “R10C5” is the cell where the tenth row and the fifth column intersect. When working with A1-style references, this is cell E10.

    R10C5 cell in Excel

Now that you understand the R1C1-style notation, you may be wondering things such as:

  • Why is the R1C1 style useful?
  • Why is the focus of this VBA tutorial the FormulaR1C1 property instead of the Range.Formula property?
  • Why should you understand R1C1-style references and the FormulaR1C1 property when working with VBA?

To answer these (and similar questions) you may have, let’s take a look at:

R1C1-Style References And The FormulaR1C1 Property: Why Are They Important And Useful

In Chapter 5 of Excel 2016 VBA and Macros, Excel authorities Bill Jelen (Mr. Excel) and Tracy Syrstad provide a very good introduction to the historical background of the A1 and R1C1 referencing styles. The short story, as explained at ExcelMate, is roughly as follows:

  • #1: Back in the early days of spreadsheets, VisiCalc (the first spreadsheet program) introduced the A1 notation. Lotus 1-2-3, a very popular spreadsheet program in the 1980s, followed suit and also used A1-style references.
  • #2: Microsoft’s Multiplan (an early spreadsheet program from Microsoft) used the R1C1-style notation.
  • #3: Lotus 1-2-3 was very popular during the 1980s.
  • #4: Eventually, as explained here, Microsoft added A1-style references. As explained in Excel 2016 VBA and Macros:

    Officially (…), Microsoft supports both styles of addressing.

For most practical purposes, nobody (or virtually nobody) uses the R1C1-style of referencing when working with Excel. However, when working with VBA, this isn’t the case.

For starters, as I show at the beginning of this post, the Macro Recorder constantly uses the Range.FormulaR1C1 property. Therefore, having a good understanding of R1C1 references allows you to read the code that the Macro Recorder creates.

However, this isn’t the main strength of the R1C1-style notation. Here’s the deal:

When you’re working with Visual Basic for Applications, R1C1-style references allow you to (for most purposes) create more efficient and powerful VBA applications. Additionally, if you want to be able to use certain features, you must use the R1C1-style notation. In the words of Mr. Excel and Tracy Syrstad (in Excel 2016 VBA and Macros):

I have to give Microsoft credit. R1C1-style formulas, you’ll grow to understand, are actually more efficient, especially when you are dealing with writing formulas in VBA. Using R1C1-style addressing enables you to write more efficient code. Plus, there are some features such as setting up array formulas that require you to enter a formula in R1C1 style.

At Chandoo.org, you can find some additional reasons why (as a general matter) you understanding the R1C1-style notation is helpful. This includes, for example, the fact that the R1C1 style may help you when working with VBA loops.

All of the above doesn’t mean that you must always use R1c1-style notation when working with Visual Basic for Applications. There are several Excel experts and power users who have (at different times) expressed that they don’t necessarily rely on the R1C1 style all the time.

Furthermore, as I explain below, there are cases where you can rely on the A1-style notation while working with VBA.

Given this, you might still wonder whether the R1C1-style notation is really more efficient than the A1 style when working with Visual Basic for Applications.

Fortunately, you don’t need to take my (or Mr. Excel’s) word. Let’s take a closer look at the R1C1-style notation to see some evidence of this:

R1C1-Style Notation: How Are Cell References Created

In a previous section, I provide an introductory explanation of how you can create cell references that use the R1C1 style. At the most basic level, you can refer to any cell by using the R1C1-style notation by concatenating the following 4 elements:

  • Element #1: The letter “R”.
  • Element #2: The reference to the number of the row where the cell is.
  • Element #3: The letter “C”.
  • Element #4: The reference to the number of the cell’s column.

I provide some introductory examples of cell references above.

When working with Excel, you can encounter (and use) 3 different types of cell references. This applies regardless of whether you’re using the A1 or the R1C1-style notation. These 3 types of cell references, as explained at office.com, are:

  • Type #1: Relative references.

    Relative references change as you copy a formula from one cell to another.

    When you’re working with A1-style references, relative references are the default. For example, when creating a relative reference to refer to the first cell of a worksheet using A1-style notation, you simply write “A1”.

  • Type #2: Absolute references.

    Absolute references don’t change as you copy a formula from one cell to another.

    As explained in the Excel 2016 Bible, absolute references use 2 dollar signs ($). One of the dollar signs ($) goes before the column identifier. The other dollar sign ($) is placed before the row identifier. Therefore, to create an absolute reference to the first cell of a worksheet using A1-style notation, you type “$A$1”.

  • Type #3: Mixed references.

    As implied by their name, mixed references are a mix of relative and absolute references. Therefore, if you’re using mixed references, either the row or the column is absolute (doesn’t change as you copy the formula from one cell to another) and the other is relative (changes as you copy the formula).

    Mixed references use a single dollar sign ($). This dollar sign is placed prior to the identifier of the item (row or column) that is absolute. For example, if you’re creating a mixed reference to the first cell of a worksheet: (i) “$A1” results in a mixed reference where the column (A) is absolute and the row (1) is relative, and (ii) “A$1” results in a reference where the column (A) is relative and the row (1) is absolute.

If you’re interested in learning more about relative, absolute and mixed cell references when using the A1-style notation, the following resources may be of interest to you:

  • Switch between relative, absolute, and mixed references at office.com.
  • Cell References at Excel Easy.
  • Relative And Absolute Cell References at GCFLearnFree.org.

Since the focus of this VBA tutorial is the R1C1-style notation, let’s take a look at how you create relative, absolute and mixed references with it:

Relative Reference With R1C1-Style Notation

It might sound crazy, but:

At its most basic level, the way in which you build relative references using the R1C1-style notation (which I explain in this section) is the main reason why R1C1-style references allow you to make your VBA code more efficient. So, even though the R1C1-style reference examples I provide below may look relatively simple, be patient. The sample Sub procedure I provide below, shows how you can use the R1C1-style notation and the Range.FormulaR1C1 property to efficiently set formulas in Excel.

Note also that, despite the usefulness of the R1C1-style notation, there are some issues you should keep in mind when creating macros that rely on such notation. I provide a thorough explanation of this topic towards the end of this blog post.

Relative references are the default in the R1C1-style notation.

R1C1-style relative references have square brackets ([ ]) around the numbers of the rows and columns.

However, relative R1C1-style references are subject to additional rules. To understand most of this, it may help if you think of relative references in the R1C1-style notation being built in the following 3 steps:

Step #1: Start On The Active Cell

Imagine that you’re currently in cell R10C5. When using A1-style notation, this is cell E10.

R1C1-style notation reference example

This cell is the base (or reference) for the relative reference you’re building.

Step #2: Move A Certain Number Of Rows Up Or Down

You specify the row of the cell you’re referring to by moving a certain number of rows up or down. For these purposes you count from the cell you’re working on (the current active cell).

The number of rows you’re moving up or down determines the number that goes after the letter “R” in an R1C1-style reference. More precisely:

  • If you use a positive number, you’re moving down the worksheet.

    Relative reference with positive number in R1C1-style

  • If you use a negative number, you’re moving up the worksheet.

    Relative reference with negative row number in R1C1-style

  • If you use no number at all, you move neither up nor down.

For example, if you’re in cell R10C5 and you want to refer to the cell immediately below it (R11C5), the first portion of the cell reference is “R[1]”.

However, if you’re referring to the cell immediately above R10C5, the first portion of the cell reference is “R[-1]”.

Finally, if you’re referring to the cell itself (creating a circular reference), the first portion of the cell reference is simply “R”.

Step #3: Move A Certain Number Of Columns To The Right Or To The Left

The rules for specifying the column to which you’re referring to are a reflection of the rules I explain above to refer to the row number. Here’s what I mean:

  • You specify the column of the cell you’re referring to by moving a certain number of columns to the right or to the left of the cell you’re working on.
  • The number of columns you move to the right or to the left determines the number that goes after the letter “C” in the R1C1-style reference.
  • Positive numbers mean you’re moving to the right along the worksheet.

    Positive column number in R1C1-style relative reference

  • Negative numbers mean you’re moving to the left along the worksheet.

    Negative column number for relative R1C1-style reference

  • No number means you’re staying on the same column.

Continuing with the same example as in the previous step #2, if you’re in cell R10C5 and want to refer to the cell to the right, the second portion of the cell reference is “C[1]”. To refer to the cell to the left of R10C5, the second portion of the reference is “C[-1]”. To refer to the cell itself (and create a circular reference), the first portion of the cell reference is “C” alone.

Let’s take a look at 4 examples of relative R1C1-style references:

Example #1 Of R1C1-Style Relative Reference

If you’re working on the first cell of the worksheet (R1C1, or A1 in A1-style notation) and want to refer to cell R8C5 (E8 in A1-style notation, you move:

  • 7 rows down; and
  • 4 columns to the right.

Therefore, the reference is “R[7]C[4]”.

Example #1 of relative R1C1 reference

Example #2 Of R1C1-Style Relative Reference

If the current active cell is R5C5 (E5 in A1-style notation) and want to refer to cell R2C2 (B2 in A1-style notation), you move:

  • 3 rows up; and
  • 3 rows to the left.

As a consequence of this, the reference is “R[-3]C[-3]”.

Example #2 of relative R1C1-style reference

Example #3 Of R1C1-Style Relative Reference

If you’re in cell R10C5 (E10 in A1-style notation) and want to refer to cell R4C7 (G4 in A1-style notation), you move:

  • 6 rows up; and
  • 2 columns to the right.

Therefore, the reference is “R[6]C[2]”.

Example #3 of relative R1C1-style reference

Example #4 Of R1C1-Style Relative Reference

If you’re in cell R8C4 (cell D8 in A1-style notation) and want to refer to cell R2C4, you move:

  • 6 rows up, and
  • Stay in the same column.

Therefore, the reference is “R[-6]C”.

Example #4 of relative R1C1-style reference

You probably get the idea. Therefore, let’s move on to…

Absolute References With R1C1-Style Notation

To build absolute references with R1C1-style notation, simply do the opposite of what you do when building relative references. That is, omit the square brackets ([ ]).

This is the style that I use above when introducing the R1C1-style notation.

For example, when creating an absolute R1C1-style reference to the first cell in a worksheet, type “R1C1”.

Mixed References With R1C1-Style Notation

To build mixed references using the R1C1-style notation, include the square brackets ([ ]) around the number of the item (row or column) you want to make relative. In other words:

  • To build a mixed R1C1-style reference where the row is relative and the column is absolute, surround the row number with square brackets ([ ]).

    Such a mixed reference looks roughly like “R[#]C#”.

  • To create a mixed R1C1-style reference in which the row is absolute and the column is relative, wrap the column number with square brackets ([ ]).

    In this case, the mixed references look roughly like “R#C[#]”.

Let’s go back to example #1 of a relative reference using the R1C1-style notation to see how a relative R1C1-style reference looks like:

In that situation, the active cell is R1C1 (A1 in A1-style notation). You’re referring to cell R8C5 (E8 in A1-style notation). The relative reference in such a situation is R[7]C[4].

In such a case, you can build the following 2 mixed references:

  • Reference #1: R8C[4]. In this case, the row is absolute and the column is relative.


    Example #1 of mixed R1C1-style reference

  • Reference #2: R[7]C5. In this reference, the row is relative and the column is absolute.

    Example #2 of mixed R1C1-style reference

Referring To A Full Row Or Column Using R1C1-Style Notation

To create a reference to all the cells within a particular row or column, simply omit the other item (row or column) of the reference. What I mean is the following:

  • To refer to a full row, omit the column identifier. Such a R1C1-style reference is of the form “R[#]” (if relative) or “R#” (if absolute).
  • To refer to a full column, omit the row identifier. An R1C1-style reference is therefore of the form “C[#]” (if relative) or “C#” (if absolute).

The rules regarding relative and absolute references, and the respective use of square brackets ([ ]) continues to be the same as I explain in the previous sections.

For example, R5 is an absolute reference to row 5.

Absolute row R1C1-style reference

Similarly, if the active cell is R1C1, C[4] refers to the full column located 4 columns to the right or R1C1 (column 5). This is a relative reference.

Relative column R1C1-style reference

Now that you have a good grasp of the R1C1-style notation, let’s take a look at the…

One of the topics of focus of this VBA tutorial is the Range.FormulaR1C1 property. Let’s take a look at its main characteristics:

Range.FormulaR1C1: Basic Description And Purpose

Range.FormulaR1C1 is a read/write property. Therefore, you can both (i) read the property or (ii) modify it.

The main purpose of the FormulaR1C1 property depends on whether you’re reading or modifying the property. More precisely:

  • If you’re fetching the current setting of the property, Range.FormulaR1C1 returns the formula (using R1C1-style notation) of the relevant range.
  • If you’re modifying the value of the property, Range.FormulaR1C1 sets the formula (using R1C1-style notation) of the range you’re working with.

The Range.FormulaR1C1 property uses the language of the macro. Therefore, the returned formula (when reading) or the set formula (when writing) are both in that language. If you’re interested in dealing with R1C1-style formulas in the language of the user, you may be interested in learning about the Range.FormulaR1C1Local property (which I explain below).

Range.FormulaR1C1: Syntax

The basic syntax of the Range.FormulaR1C1 property is as follows:

expression.FormulaR1C1

“expression” is a variable representing a Range object.

Range.FormulaR1C1: Reading The Property

When you use the Range.FormulaR1C1 property for purposes of returning the formula of a particular range, the exact behavior of the property varies slightly depending on the contents of the relevant range. More precisely, as explained at the Microsoft Dev Center:

  • If a cell contains a constant, Formula R1C1 returns the constant.
  • If the cell is empty, FormulaR1C1 returns an empty string.
  • If the cell contains a formula, FormulaR1C1 returns the formula (i) as a string and (ii) using the same format in which it’s displayed in the Formula Bar (even with the equal sign (=)).

Range.FormulaR1C1: Working With Ranges

If you use the Range.FormulaR1C1 property to set the formula of a multiple-cell range, Excel fills all the cells of the relevant range with the formula. Generally, as I show below, Excel adjusts the cell references automatically.

You can see how the FormulaR1C1 property works with multi-cell ranges in practice by taking a look at the practical examples below.

Range.FormulaR1C1: Setting A Date

If you use the Range.FormulaR1C1 property to set the value or formula of a particular cell to a date, Excel proceeds as follows:

  • Step #1: It checks whether the cell you’re working with is formatted using a date or time number format.
  • Step #2: If the condition is met, and the cell already uses a date or time number format, Excel leaves the format untouched.

    However, if the cell isn’t formatted using a date or time number format, Excel sets the format of the cell to be the default short date number format.

Range.FormulaR1C1Local Property And Language Considerations

As explained by Excel authorities Dick Kusleika and Mike Alexander in Excel 2016 Power Programming with VBA:

In general, you need not be concerned with the language in which you write your VBA code.

The reason for this, as explained by Kusleika and Alexander, is that Excel uses 2 object libraries:

  • Excel’s object library.
  • The VBA object library.

Excel always sets the English version of both libraries as the default. This is the case regardless of which language you use in Excel.

Working with formulas is, generally, one of the exceptions to the above rule. In other words, if you’re working in a particular VBA application whose users may have different language settings, language compatibility may be an issue you should consider.

Let’s take a closer look at this point:

Excel Formulas And Language Considerations

As a general matter, Excel functions are localized. As a consequence, the name of a particular function, such as IFERROR varies depending on the language in which Excel runs. Let me explain what I mean:

In this blog post, I explain several text functions such as LEFT, RIGHT, MID, LEN, FIND and SEARCH. These, however, are the names used by the English version of Excel. The names of the functions change depending on the particular language you’re using Excel in.

The following table shows the names of these particular functions in 10 different languages. I prepared the translation using the Excel-Translator.

#1 English LEFT RIGHT MID LEN FIND SEARCH
#2 Spanish IZQUIERDA DERECHA EXTRAE LARGO ENCONTRAR HALLAR
#3 German LINKS RECHTS TEIL LÄNGE FINDEN SUCHEN
#4 French GAUCHE DROITE STXT NBCAR TROUVE CHERCHE
#5 Dutch LINKS RECHTS DEEL LENGTE VIND.ALLES VIND.SPEC
#6 Italian SINISTRA DESTRA STRINGA.ESTRAI LUNGHEZZA TROVA RICERCA
#7 Portuguese (Brazil) ESQUERDA DIREITA EXT.TEXTO NÚM.CARACT PROCURAR LOCALIZAR
#8 Polish LEWY PRAWY FRAGMENT.TEKSTU ZNAJDŹ SZUKAJ.TEKST
#9 Danish VENSTRE HØJRE MIDT LÆNGDE FIND SØG
#10 Turkish SOLDAN SAĞDAN PARÇAAL UZUNLUK BUL MBUL

Excel MVP Mourad Louha is an expert in this topic and has invested a substantial amount of time and resources in the development of the Excel-Translator. Mourad explains the challenge when working with Excel functions in a multilingual setting quite clearly as follows:

If you send your Excel file to someone using a different language for Excel than you, the functions and formulas used in the workbook are automatically translated by Excel when opening the file. However, the automatic translation usually does not work, if you directly insert foreign language formulas into your worksheet.

When working with the FormulaR1C1 property, you fall within the second scenario (in bold). In other words:

If you’re reading or setting a formula by using the FormulaR1C1 VBA property, the functions are usually not automatically translated.

The easiest way to deal with language compatibility concerns when working with the FormulaR1C1 property is to use the local version of the FormulaR1C1 property:

Range.FormulaR1C1Local Property

To understand why the LanguageR1C1Local may be helpful, let’s go back to what I say above about the language used by the Range.FormulaR1C1. That is, the FormulaR1C1 property uses the language of the macro.

On the other hand, the Range.FormulaR1C1Local property, which I cover in this section, uses the language of the user.

For practical purposes, other than this important aspect, all of the comments I make above regarding the Range.FormulaR1C1 property are applicable. More precisely:

  • Range.FormulaR1C1Local is a read/write property.
  • You can use Range.FormulaR1C1Local to return (read) or set (write) the formula of a range using R1C1-style notation.
  • The basic syntax of Range.FormulaR1C1Local is “expression.FormulaR1C1Local”.

    “expression” represents a Range object.

  • The item returned by Range.FormulaR1C1Local (when used for reading purposes) depends on whether the cell (i) is empty, (ii) contains a constant, or (iii) contains a formula.

    I explain further details of this behavior above.

  • When you use the Range.FormulaR1C1Local property to set a value or formula to a date: (i) Excel checks whether the cell is formatted using a date or time number format and (ii) sets the format to the default short date number format if the cell isn’t formatted as a date or time.
  • When working with ranges, the remarks I make in connection with Range.FormulaR1C1 throughout this tutorial are also applicable to Range.FormulaR1C1Local.

In other words:

  • When working with the FormulaR1C1 property and reading this tutorial, bear in mind the following:

    #1: Range.FormulaR1C1 uses the language of the macro.

    #2: Range.FormulaR1C1Local uses the language of the user.

  • Other than the above and for most practical purposes, Range.FormulaR1C1 and Range.FormulaR1C1Local behave and can be treated materially the same.

Range.FormulaR1C1 Property Example: Setting The Formula Of A Cell Range To Create A Table

This Excel VBA R1C1-Style Notation and FormulaR1C1 Property Tutorial is accompanied by an Excel workbook containing the data and macros I use. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

For this example, let’s assume that you want to want to prepare a table that shows different combinations of the total revenue generated by 2 different revenue streams. The revenue generated by these streams is listed in $100 increments in the following cell ranges:

  • C5 (R5C3 in R1C1-style notation) to CX5 (R5C102 in R1C1-style notation).
  • B6 (R6C2 in R1C1-style notation) to B105 (R105C2 in R1C1-style notation).

Column and row headers for FormulaR1C1 example

In order to fill the table and show the different total revenue combinations, you must add the following 2 numbers in each cell:

  • The value at the top of the relevant column (in row 5); and
  • The value at the beginning of the relevant row (in column B or 2).

Setting up the formula manually is relatively straightforward. You can do this in the following 2 easy steps:

  • Step #1: Enter the relevant formula in the first cell of the table.

    In this particular case, the formula I enter is “=SUM(C$5,$B6)”. Notice that the cell references are mixed: (i) in C$5, the row number is absolute and, therefore, isn’t adjusted when the formula is copied to other cells, and (ii) in $B6, the column number is absolute and isn’t adjusted as the formula is copied and pasted.

    Sample formula with mixed references

  • Step #2: Copy the formula and paste it in all the relevant cells of the table.

    As expected, the table is filled with the appropriate formulas. Notice, for example, how the formula in cell O29 appropriately adds the cell at the top of the column (O5) and at the beginning of the row (B29).

    Sample table and cell with formula

The following screenshot shows some of the formulas within this worksheet. Notice how Excel (pretty much) rewrites a portion of the formula for each cell in order to adjust the cell references.

Example of formulas with A1-style notation

In the words of Mr. Excel and Tracy Syrstad (in Excel 2016 VBA and Macros):

It seems intimidating to consider having a macro enter all these different formulas.

The reason for this, however, is because the formulas in the screenshots above use A1-style notation.

The following screenshot shows the same portion of the table we’re working on as that above. The only difference is that, in the image below, R1C1-style notation is used.

Example of R1C1-style formulas

Notice that, when using R1C1-style notation, all of the formulas in the table are exactly the same.

As I explain above, you can use the Range.FormulaR1C1 property to enter such a formula in such a range.

The following sample macro (FormulaR1C1_Table) achieves this:

Sample macro code with FormulaR1C1

This Sub procedure consists of a single statement:

Range(“C6:CX105”).FormulaR1C1 = “=SUM(R5C,RC2)”

Let’s take a look at its 3 main components separately to understand how the macro works:

Sample Sub procedure with FormulaR1C1

Item #1: Range(“C6:CX105”)

This makes reference to the Application.Range property. Within the syntax of the FormulaR1C1 property that I introduce above, this item takes the place of the expression that returns a Range object.

More precisely, this statement returns the range of cells from C6 to CX105 of the current active worksheet.

The fully qualified reference is “Application.ActiveSheet.Range(“C6:CX105”). However, as I explain on this VBA tutorial about Excel’s Object Model, you can simplify the reference by assuming the following default objects:

  • The Application object.
  • The Active Workbook.
  • The Active Sheet.

Item #2: FormulaR1C1 =

This item makes reference to the FormulaR1C1 property.

As I explain in the tutorial about VBA Object Properties, whenever you’re setting a property value, you use an equal sign (=) to separate the property name (FormulaR1C1) from the property value (item #3 below).

Item #3: “=SUM(R5C,RC2)”

This item is the value that is set for the FormulaR1C1 property of all the cells within the range returned by item #1 above. This formula is the one I show in the screenshot above.

The following GIF shows what happens when I execute the sample FormulaR1C1_Table macro. Notice how, as expected, Excel appropriately fills all the cells within the table.

Example of macro execution with FormulaR1C1

Let’s make an additional check by reviewing the formula of cell O29. Notice that, in this case, the formula is exactly the same as that which resulted from the manual process I show above (=SUM(O$5,$B29)).

Formulas set with FormulaR1C1 macro

Considering all that I’ve said throughout this VBA tutorial regarding the advantages of using R1C1-style notation and the Range.FormulaR1C1 property when working with VBA, you may be surprised by what I explain in the following section:

Setting The Formula Of A Cell Range To Create A Table With The Range.Formula Property

Strictly speaking, you can replicate the results of the sample FormulaR1C1_Table macro above by using A1-style notation and the Range.Formula property.

The focus of this particular blog post isn’t the Range.Formula property. I may cover this topic in a future tutorial. If you want to be notified whenever I publish new content in Power Spreadsheets, please register for our Newsletter by entering your email address below:

As explained by Excel expert Andrew Poulsom at MrExcel.com, the Range.Formula property behaves very similarly to the Range.FormulaR1C1 property I explain above. In other words, you can use the Formula property to either:

  • Return (read) the formula (using A1-style notation) of the range you’re working with.
  • Set the formula (using A1-style notation) of the relevant range.

So, for purposes of this explanation, the Range.Formula and Range.FormulaR1C1 properties achieve the same purpose with 1 basic difference:

The FormulaR1C1 property uses R1C1-style notation. The Formula property uses A1-style notation.

The following sample macro (Formula_Table) is the equivalent of the FormulaR1C1_Table example macro above.

Example VBA code with Range.Formula property

The single statement in the Sub procedure is substantially the same. The only 2 differences between the 2 macros are the following:

Sample macro code with Range.Formula property

  • Difference #1: FormulaR1C1_Table uses the Range.FormulaR1C1 property. Formula_Table uses the Range.Formula property.
  • Difference #2: As a consequence of the above, the formula set by FormulaR1C1_Table uses R1C1-style notation. The formula set by Formula_Table uses A1-style notation.

    Note that, in this particular case, the formula that I use in the VBA code is that corresponding to the first cell of the table (cell C6). As I explain further below, Excel automatically adjusts the formula for the other cells in the table.

The following GIF shows the what happens in Excel when I execute the sample Formula_Table macro. Notice that the results are substantially the same as those obtained when executing the FormulaR1C1_Table macro above.

Execution of macro example with Formula property

You can also check the formula in cell O29 again (as I did above). The formula is exactly the same as that obtained when carrying out the process manually or executing the FormulaR1C1_Table macro (=SUM(O$5,$B29)).

Formulas set by macro with Range.Formula property

The reason for this, as explained in Excel 2016 VBA and Macros, is that Excel actually carries out the following 3 steps whenever you enter an A1-style formula:

  • Step #1: Converts the A1-style formula to an R1C1-style formula, as I explain above.
  • Step #2: Enters the converted R1C1-style formula in the entire range.
  • Step #3: Displays the R1C1-style formulas using A1-style notation.

The consequence of this is that the macro roughly mirrors the manual process that I explain above. That 2-step process is as follows:

  • Step #1: The relevant formula is entered in the first cell of the table (cell C6).
  • Step #2: The formula is copied and pasted in all the cells of the table. Excel automatically adjusts the cell references.

So, strictly speaking, you can use both the FormulaR1C1 and the Formula properties to enter a formula in a particular range of cells.

Macros That Rely On Relative References: Avoid This Error

In a previous section, I provide a thorough explanation of how to use relative references when working with the R1C1-style notation.

When working with macros for purposes of creating relative references, there’s a particular behavior that you need to be aware of as it can be the source of mistakes. This is more thoroughly explained by experts Bill Jelen (Mr. Excel) and Tracy Syrstad in Excel 2016 VBA and Macros.

To understand how this can happen, let’s go back to the example I provide at the beginning of this blog post. At that point, I enter numbers 1 through 5 in cells B5 to B9.

Excel worksheet with data for example

For the sake of this example, I create the following sample macro (FormulaR1C1_Error).

Example of macro code with FormulaR1C1 property

This sample macro proceeds as follows:

  • Step #1: Uses the Application.ActiveCell property to return the current active cell.
  • Step #2: Uses the Range.FormulaR1C1 property to set the formula of the active cell obtained in step #1 above. The formula is, simply, a relative reference to the cell located 5 rows above (R[-5]) and 1 column to the left (C[-1]) of the current active cell.

This macro isn’t extremely useful for practical purposes. I’m just using it to get a point across

The following GIF shows what happens when I execute the macro while the active cell is cell C10. Notice that, as expected, Excel enters a reference to the cell located 5 rows above and 1 column to the left of C10. That is cell B5, whose value is 1.

Macro execution with FormulaR1C1 relative references

The macro works properly. If you execute the macro for the 4 cells below cell C10 (C11 to C14), the macro enters references to the values that are already entered in cells B6 to B9.

However, take a look at what happens when I execute this macro while the active cell is A5:

Execution of macro with relative references and mistake

Notice that Excel doesn’t return an error. It rather makes reference to cell XFD1048576.

Excel formula with mistake from FormulaR1C1

What’s the bottom line?

In such situation, Excel goes around the worksheet. Therefore:

  • If your macro makes reference to a cell that is “above” row 1, Excel wraps around and goes to the last row of the worksheet to continue searching for the referred cell.
  • If your macro makes reference to a cell that is to “the left” of column A (or column 1 in R1C1-style notation), Excel wraps around and goes to the last column of the worksheet to continue searching for the relevant cell.

In the example above, both things of these things happened:

  • The macro created a reference to a cell 1 row “above” row 1. Once Excel wraps around, this results in the last row of the worksheet (row 1,048,576 in recent Excel versions).
  • The reference was to a cell 1 column to “the left” of column A (or 1 in R1C1-style). When Excel wraps around, this results in the last column of the worksheet (XFD in A1-style or 16,384 in R1C1-style notation).

The consequence of all of this is that Excel creates the reference that appears in the screenshot above to cell XFD1048576.

I assume that, unless you’re facing a very particular situation or scenario, this isn’t the behavior you want from your macros.

Conclusion

If you’ve completed this VBA tutorial, you now have enough knowledge to start using the R1C1-style notation and the Range.FormulaR1C1 property for purposes of making your Excel macros more efficient, flexible and powerful. Among other topics, you know:

  • What are the A1 and the R1C1-style notations.
  • Why are the R1C1-style notation and the FormulaR1C1 property useful and important.
  • How you can create absolute, relative and mixed references when working with the R1C1-style, and a particular behavior that you should take into consideration when creating relative references within VBA to avoid potential mistakes.
  • What are the main characteristics of the Formula.R1C1 property.
  • What is the Range.FormulaR1C1Local property, and how you can use it to deal with particular language considerations that arise if you work in a multilingual environment.

In addition to the above, you’ve seen a practical example showing how you can use the Range.FormulaR1C1 (or alternatively the Range.Formula) property for purposes of specifying the formula of a large range of cells.

This Excel VBA R1C1-Style Notation and FormulaR1C1 Property Tutorial is accompanied by an Excel workbook containing the data and macros I use above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Books Referenced In This Excel Tutorial

  • Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
  • Jelen, Bill and Syrstad, Tracy (2015). Excel 2016 VBA and Macros. Indianapolis, IN: Pearson Education, Inc.
  • Walkenbach, John (2015). Microsoft Excel 2016 Bible. Indianapolis, IN: John Wiley & Sons Inc.

In Excel, there are two kinds of cell reference styles first is A1 and the second is R1C1. Well, most Excel users don’t even know about the existence of the R1C1 reference style.

But some users love to use it and found it more convenient than A1. The R1C1 style is a kind of old one.

It was first introduced in Multiplan which was developed by Microsoft for Apple Macintosh.

But after a few years, Microsoft started to use the A1 style so that people who migrated from Lotus would find it familiar, but R1C1 has been always there in Excel.

There are fewer additional benefits in R1C1 than in A1. And today in this post, I’d like to share with you all the aspects of using the R1C1 reference style.

So without any further ado, let’s explore this thing.

Difference Between A1 and R1C Reference Style

In the A1 reference style, you have the column name as an alphabet and the row name as a number and when you select the A1 cell that means you are in column A and row 1.

But in R1C1 both column and row are in numbers.

So, when you select cell A1 it shows you R1C1, which means row 1 and column 1, and if you go to A2 then it will be R2C1.

Difference Between A1 Reference Style & R1C1 Reference Style

In the above two examples, you have the same active cell, but different cell addresses. The real difference comes when you write formulas and use a reference to other cells.

In R1C1, when you refer to a cell it creates the address of referred cell using its distance from the active cell.

For example, if you refer to cell B5 from cell A1 it will show the address of B5 as R[4]C[1].

refer b5 from a1 using r1c1 reference style

Now, just think this way. Cell B5 is 4 rows down and 1 column ahead of cell A1, so that’s why its address is R[4]C[1].

But here’s the kicker. If you refer to the same cell from a different cell then its address will be different.

The point to understand is, In the R1C1 reference style, there is no permanent address for a cell (if you are using relative reference), so a cell’s address dependents ob from where you are referring to it.

Using the R1C1 reference is a realistic approach to working with cell references.

Ahead of this post, I will detail this approach. But first of all, let’s learn to activate it.

How to Activate R1C1 Cell Reference in Excel – Simple Steps

To use R1C1, the first thing you need to do is to activate it and for this, you can use any of the below methods.

From Excel Options

Please follow these simple steps to set the R1C1 reference as default.

  1. Go to File Tab ➜ Option ➜ Formulas ➜ Working with formulas.
  2. Tick mark “R1C1 Reference Style”.
  3. Click OK.
activate r1c1 reference style from options in Excel

Using a VBA Code

If you are macro savvy and want to save time then you can use the below macro code to toggle between cell reference styles.

Sub ChangeCellRef()
If Application.ReferenceStyle = xlA1 Then
Application.ReferenceStyle = xlR1C1
Else
Application.ReferenceStyle = xlA1
End If
End Sub

Once you make R1C1 your default reference style all the references in formulas in all the workbooks will change.

How R1C1 Reference Style Works

Now at this point, you are clear about one thing in R1C1, you have row number and column number.

numbers for column and row in r1c1 style

But to understand how it works, you need to learn all the different kinds of references.

A1 Reference Style R1C1 Reference Style Reference Type
A1 R[-4]C[-1] Relative Reference
$A$1 R1C1 Absolute Reference
$A1 R[-4]C1 Relative Row and Absolute Column
A$1 R1C[-1] Absolute Row and Relative Column
different kinds of references

Just like A1, you can use four different kinds of references in R1C1 as mentioned in the above table. But now, let’s dig deeper into each type of reference.

1. Relative R1C1 Reference

Using relative reference in R1C1 is quite simple. In this reference style, when you refer to a cell, it creates the address of the referred cell using its distance from the active cell.

using relative reference in r1c1 style

If you want to go to a column on the right side of the active cell, the number will be positive, or if the left side then a negative number. And same for the row, a positive number for the below and a negative for the above active row.

an example for relative r1c1 reference style

In the above example, we have used the relative reference to multiply a cell that is 1 column before the cell with a cell that is 2 columns before.

If you copy and paste this formula to any other cell in your worksheet it will always multiply the cell which is 1 column before the active cell with a cell that are 2 columns before.

2. Absolute R1C1 Reference

I’m sure you have noticed this thing in the above example row and column numbers have square brackets. Let me show you what happens when you don’t use square brackets in the cell reference.

 a simple example to understand absolute reference in r1c1

In the above example, when you are using row 2 and column 1 without square brackets this means that the cell you are referring to is exactly in row 2 and column 1.

Here’s the real thing: In R1C1, when you want to use the absolute reference you can skip using square brackets and Excel will treat cell R1C1 (cell A1) as the starting point.

Let me show you an example.

an example for relative r1c1 reference style in excel

In the above example, we have multiplied cell R2C3 which is in the 2nd row, and the 3rd column from R1C1 (cell A1) with a cell that is 1 column before from the active cell.

R2C3 is without square brackets and when we drag down the formula, the cell reference doesn’t change with it.

3. Semi Absolute/Relative R1C1

This is one of the most used reference styles where you can make the only column or row, absolute or relative. Let me show you an example.

using semi absolute and relative reference with r1c1

In the above example, we have multiplied the value in the first row by the value in the first column.

  • RC1: When you skip specifying the row number then Excel treats the active cell’s row for reference. So here column will remain the same but the row will change once you drag the formula in all the cells.
  • R1C: When you skip specifying the column number then Excel treats the active cell’s column for reference. So here row will remain the same but the column will change once you drag the formula in all the cells.

Using R1C1 Reference in Formulas

Once you switch from A1 to R1C1 style, you will see all the formulas in your worksheet have changed.

Might be the first time you find them confusing, but in reality, they are quite simple. Let me show you how this thing works with simple sum formula.

In the below example, we have a data table with monthly sales of 10 products with a total column at the end.

a data table with a1 style

And here you are using the A1 reference style.

In this reference style, each total cell has a different formula using a different cell reference.

But as soon as, you change the reference from A1 to R1C1, all the formulas have changed and they are the same in each total cell.

In all ten cells, we have the below formula.

=SUM(RC[-12]:RC[-1])
a data table with r1c1 style

This formula says: “Sum the range of values from the cell 12 columns to the left (C[–12]) in the same row through the cell that is one column to the left (C[–1]) in the same row.

Because in all the cells where we are calculating the total, the range of values is in the same order and that’s why we have the same formula for all the cells.

Tip from Excel 2016 All-in-One For Dummies: You can use the R1C1 notation to check that you’ve copied all the formulas in a spreadsheet table correctly. Move the cell cursor through all the cells with copied formulas in the table. When R1C1 notation is in effect, all copies of an original formula across an entire row or down an entire table column should be identical when displayed on the Formula bar as you make their cells current.

Using R1C1 Reference in VBA

When you record a macro, you can see that Excel uses the R1C1 formula to reference while referring to cells and ranges.

using r1c1 reference in vba

And, if you know how to use the R1C1 notion, you easily edit the recorded macro codes and save a ton of time. For this, you need to understand the working of the FormulaR1C1 method.

Let’s say you want to enter a formula in the active cell where you need to multiply two cells that are on the left side of the active cell.

Sub R1C1Style()
Selection.FormulaR1C1 = "=RC[-2]*RC[-1]"
End Sub

You are multiplying the cell which is one column left with a cell which is two columns left from the active cell. Now the best part of this is:

When you change the location of your table it will work in the same pattern, you don’t have to make any changes in your code. But, what will happen if we use the A1 reference here instead of R1C1:

We can’t use this code for every cell because the cell reference would be fixed (Otherwise we need to use the Offset property). Get more insight into Formula.R1C1 method from Jorge’s guide.

Conclusion

While understanding the R1C1 you will feel some fear, but once you overcome this, you will have a new flexible approach to working in Excel.

One thing which I just forgot to tell you is that you can use F4 to switch between relative, absolute, and semi-relative cell references. Here are some points which we have covered in this tutorial and which you need to keep in mind.

  1. In R1C1, R stands for a row and C stand for a column.
  2. To refer to a row that is below and a column that is ahead of the active cell you can use a positive number.
  3. To refer to a row that is above and a column that is behind the active cell you can use a negative number.
  4. When you use a row or column number without a square bracket, Excel will treat it as an absolute reference.
  5. In VBA, to use R1C1 you need to use the FormulaR1C1 method.

I hope you have found this post helpful and now tell me one thing.

Will you start using R1C1?

Make sure to share your views with me in the comment section, I’d love to hear from you. And please, don’t forget to share this post with your friends, I am sure they will appreciate it.

In this Article

  • Formulas in VBA
  • Macro Recorder and Cell Formulas
  • VBA FormulaR1C1 Property
    • Absolute References
    • Relative References
    • Mixed References
  • VBA Formula Property
  • VBA Formula Tips
    • Formula With Variable
    • Formula Quotations
    • Assign Cell Formula to String Variable
    • Different Ways to Add Formulas to a Cell
    • Refresh Formulas

This tutorial will teach you how to create cell formulas using VBA.

Formulas in VBA

Using VBA, you can write formulas directly to Ranges or Cells in Excel. It looks like this:

Sub Formula_Example()

    'Assign a hard-coded formula to a single cell
    Range("b3").Formula = "=b1+b2"
    
    'Assign a flexible formula to a range of cells
    Range("d1:d100").FormulaR1C1 = "=RC2+RC3"

End Sub

There are two Range properties you will need to know:

  • .Formula – Creates an exact formula (hard-coded cell references). Good for adding a formula to a single cell.
  • .FormulaR1C1 – Creates a flexible formula. Good for adding formulas to a range of cells where cell references should change.

For simple formulas, it’s fine to use the .Formula Property.  However, for everything else, we recommend using the Macro Recorder

Macro Recorder and Cell Formulas

The Macro Recorder is our go-to tool for writing cell formulas with VBA.  You can simply:

  • Start recording
  • Type the formula (with relative / absolute references as needed) into the cell & press enter
  • Stop recording
  • Open VBA and review the formula, adapting as needed and copying+pasting the code where needed.

I find it’s much easier to enter a formula into a cell than to type the corresponding formula in VBA.

vba formula formular1c1

Notice a couple of things:

  • The Macro Recorder will always use the .FormulaR1C1 property
  • The Macro Recorder recognizes Absolute vs. Relative Cell References

VBA FormulaR1C1 Property

The FormulaR1C1 property uses R1C1-style cell referencing (as opposed to the standard A1-style you are accustomed to seeing in Excel).

Here are some examples:

Sub FormulaR1C1_Examples()

    'Reference D5 (Absolute)
    '=$D$5
    Range("a1").FormulaR1C1 = "=R5C4"
    
    'Reference D5 (Relative) from cell A1
    '=D5
    Range("a1").FormulaR1C1 = "=R[4]C[3]"
    
    'Reference D5 (Absolute Row, Relative Column) from cell A1
    '=D$5
    Range("a1").FormulaR1C1 = "=R5C[3]"
    
    'Reference D5 (Relative Row, Absolute Column) from cell A1
    '=$D5
    Range("a1").FormulaR1C1 = "=R[4]C4"

End Sub

Notice that the R1C1-style cell referencing allows you to set absolute or relative references.

Absolute References

In standard A1 notation an absolute reference looks like this: “=$C$2”.  In R1C1 notation it looks like this: “=R2C3”.

To create an Absolute cell reference using R1C1-style type:

  • R + Row number
  • C + Column number

Example:  R2C3 would represent cell $C$2 (C is the 3rd column).

    'Reference D5 (Absolute)
    '=$D$5
    Range("a1").FormulaR1C1 = "=R5C4"

Relative References

Relative cell references are cell references that “move” when the formula is moved.

In standard A1 notation they look like this: “=C2”. In R1C1 notation, you use brackets [] to offset the cell reference from the current cell.

Example: Entering formula “=R[1]C[1]” in cell B3 would reference cell D4 (the cell 1 row below and 1 column to the right of the formula cell).

Use negative numbers to reference cells above or to the left of the current cell.

    'Reference D5 (Relative) from cell A1
    '=D5
    Range("a1").FormulaR1C1 = "=R[4]C[3]"

Mixed References

Cell references can be partially relative and partially absolute.  Example:

    'Reference D5 (Relative Row, Absolute Column) from cell A1
    '=$D5
    Range("a1").FormulaR1C1 = "=R[4]C4"

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

VBA Formula Property

When setting formulas with the .Formula Property you will always use A1-style notation.  You enter the formula just like you would in an Excel cell, except surrounded by quotations:

    'Assign a hard-coded formula to a single cell
    Range("b3").Formula = "=b1+b2"

VBA Formula Tips

Formula With Variable

When working with Formulas in VBA, it’s very common to want to use variables within the cell formulas.  To use variables, you use & to combine the variables with the rest of the formula string. Example:

Sub Formula_Variable()
    Dim colNum As Long
    colNum = 4

    Range("a1").FormulaR1C1 = "=R1C" & colNum & "+R2C" & colNum

End Sub

VBA Programming | Code Generator does work for you!

Formula Quotations

If you need to add a quotation (“) within a formula, enter the quotation twice (“”):

vba formula quotations

Sub Macro2()
    Range("B3").FormulaR1C1 = "=TEXT(RC[-1],""mm/dd/yyyy"")"
End Sub

A single quotation (“) signifies to VBA the end of a string of text. Whereas a double quotation (“”) is treated like a quotation within the string of text.

Similarly, use 3 quotation marks (“””) to surround a string with a quotation mark (“)

MsgBox """Use 3 to surround a string with quotes"""
' This will print <"Use 3 to surround a string with quotes"> immediate window

Assign Cell Formula to String Variable

We can read the formula in a given cell or range and assign it to a string variable:

'Assign Cell Formula to Variable
Dim strFormula as String
strFormula = Range("B1").Formula

Different Ways to Add Formulas to a Cell

Here are a few more examples for how to assign a formula to a cell:

  1. Directly Assign Formula
  2. Define a String Variable Containing the Formula
  3. Use Variables to Create Formula
Sub MoreFormulaExamples ()
' Alternate ways to add SUM formula
' to cell B1
'
  Dim strFormula as String
  Dim cell as Range
  dim fromRow as long, toRow as long

  Set cell = Range("B1")

  ' Directly assigning a String
  cell.Formula = "=SUM(A1:A10)"

  ' Storing string to a variable
  ' and assigning to "Formula" property
  strFormula = "=SUM(A1:A10)"
  cell.Formula = strFormula

  ' Using variables to build a string 
  ' and assigning it to "Formula" property
  fromRow = 1
  toRow   = 10
  strFormula = "=SUM(A" & fromValue & ":A" & toValue & ")
  cell.Formula = strFormula
End Sub

Refresh Formulas

As a reminder, to refresh formulas, you can use the Calculate command:

Calculate

To refresh single formula, range, or entire worksheet use .Calculate instead:

Sheets("Sheet1").Range("a1:a10").Calculate

Here’s some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).

Examples:

  • R[2]C refers to the cell two rows below the cell in which the
    formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

In R1C1, “R” refers to row, while “C” refers to column. Formula R1C1 allows you set or retrieve formula for a cell, using relative row and column.

Why do you need FormulaR1C1?

For example, you want to set a formula in C2 to sum A2 and B2, you can type

Range("C2").formula= "=A2+B2" or
Range("C2").Value = "=A2+B2"

Instead of hard code “A2+B2”, you can also tell Excel to sum the two cells on the left of the formula cell using FormulaR1C1.

“A2+B2” works well until you insert a new column before A column, where the old A column becomes B, old B column becomes C ! Since you already hard code C2 = A2+B2, the formula will not change and the formula is messed up.

However, if your formula Cell C2 is dynamic, such as Named Range, after inserting a column the reference Range will become D2, and you can tell Excel to sum the two cells on the left, thats why FormulaR1C1 is useful.

Syntax

To retrieve a formula from a Range

variableName = Range.FormulaR1C1

To set a formula for a Range

Range.FormulaR1C1 = "=R[x]C[y]" or
Range.Value = "=R[x]C[y]"

x and y are the coordinate relative to the formula Cell

where x is the number of rows right to formula Cell  (negative value means left to the formula Cell)

where y is the column down from the formula Cell (negative value means up from the formula Cell)

You can omit the square brackets for x and y if the values are positive, which will cause the Cell to turn into absolute values with $

Note that when you set a formula, the result of Range.FormulaR1c1 and Range.Value are the same, the only difference is when you retrieve the value from the Range

VBA code Return
Msgbox(Range(“C2”).value) numeric value of A2+B2
Msgbox(Range(“C2”).formulaR1C1) =RC[-2]+RC[-1]

Example of using FormulaR1C1 to set formula

In worksheet, by default, Excel convert your formula to R1C1 but you cannot see it unless you enable “R1C1 Reference Style”.  Therefore, type the below in worksheet is equivalent to adding R1C1 style.

Excel_formulaR1C1_01

In VBA

Formula Return Explanation
Range(“C2”).FormulaR1C1 = “=RC[-2]” 1 Refer to the cell 2 columns left
Range(“C2”).FormulaR1C1 = “=R[1]C[-2]” 2 Refer to the cell 1 row down and 2 columns left

Recommended Readings

Excel worksheet R1C1 reference style

 Outbound References

http://msdn.microsoft.com/en-us/library/office/ff823188%28v=office.15%29.aspx

Like this post? Please share to your friends:
  • Vba excel формула с переменной
  • Vba excel формула не пересчитывает
  • Vba excel формула массива
  • Vba excel формула листа
  • Vba excel указать лист