Вставка формулы со ссылками в стиле 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 одинаковы, их можно вставить сразу, без использования цикла, во весь диапазон.
- Remove From My Forums
-
Question
-
Hello,
Here is my problème :
In my Excel worksheet cell, I have a formula :
=»Table of Personal»&» «&»»&+C2&»year»&» in»&» «&+Zveno_Name
I don’t know how to insert this formula from my VBA code
Sheets(«March»).[A17].Formula = ??
Anyone knows how to do it?
Thanks in advanced
Answers
-
The formula itself can be simplified to
=»Table of Personal «&C2&» year in «&Zveno_Name
To create this formula in VBA, you can use
Worksheets("March").Range("A17").Formula = "=""Table of Personal ""&C2&"" year in ""&Zveno_Name"
Note that the double quotes » within the formula have been doubled to «». This is necessary because the entire formula is enclosed in double quotes.
Regards, Hans Vogelaar
-
Proposed as answer by
Wednesday, October 24, 2012 10:36 AM
-
Marked as answer by
Quist Zhang
Thursday, November 1, 2012 6:28 AM
-
Proposed as answer by
-
also a very easy for newbies to learn how to insert formula in VBA form is by «recording the macro».
Under Developper tab (2010)> Record Macro > then do the action.
You will notice all selected cell will be recorded. ALT + F11, you will find Modules folder > module one. You will see that the formula is recorded there.
regards.
Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or «Mark as Answer» if it solves your question. This will help to contribute to the forum.
-
Proposed as answer by
Asadulla JavedEditor
Thursday, October 25, 2012 6:41 AM -
Marked as answer by
Quist Zhang
Thursday, November 1, 2012 6:28 AM
-
Proposed as answer by
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.
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!
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 (“”):
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:
- Directly Assign Formula
- Define a String Variable Containing the Formula
- 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
Содержание
- Excel VBA Formulas – The Ultimate Guide
- Formulas in VBA
- Macro Recorder and Cell Formulas
- VBA FormulaR1C1 Property
- Absolute References
- Relative References
- Mixed References
- VBA Coding Made Easy
- 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
- VBA Code Examples Add-in
- VBA Excel. Вставка формулы в ячейку
- Свойство Range.FormulaLocal
- Свойство Range.FormulaR1C1Local
- 19 комментариев для “VBA Excel. Вставка формулы в ячейку”
- Insert formula in excel with vba
- Answered by:
- Question
- Answers
- All replies
- Insert formula in excel with vba
- Answered by:
- Question
- Answers
- All replies
Excel VBA Formulas – The Ultimate Guide
In this Article
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:
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.
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:
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).
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.
Mixed References
Cell references can be partially relative and partially absolute. Example:
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!
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:
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:
Formula Quotations
If you need to add a quotation (“) within a formula, enter the quotation twice (“”):
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 (“)
Assign Cell Formula to String Variable
Different Ways to Add Formulas to a Cell
Here are a few more examples for how to assign a formula to a cell:
- Directly Assign Formula
- Define a String Variable Containing the Formula
- Use Variables to Create Formula
Refresh Formulas
As a reminder, to refresh formulas, you can use the Calculate command:
To refresh single formula, range, or entire worksheet use .Calculate instead:
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Excel. Вставка формулы в ячейку
Вставка формулы со ссылками в стиле A1 и R1C1 в ячейку (диапазон) из кода VBA Excel. Свойства Range.FormulaLocal и Range.FormulaR1C1Local.
Свойство Range.FormulaLocal
В качестве примера будем использовать диапазон A1:E10, заполненный числами, которые необходимо сложить построчно и результат отобразить в столбце F:
Примеры вставки формул суммирования в ячейку F1:
Пример вставки формул суммирования со ссылками в стиле A1 в диапазон F1:F10:
В этой статье я не рассматриваю свойство Range.Formula, но если вы решите его применить для вставки формулы в ячейку, используйте англоязычные функции, а в качестве разделителей аргументов — запятые (,) вместо точек с запятой (;):
После вставки формула автоматически преобразуется в локальную (на языке пользователя).
Свойство Range.FormulaR1C1Local
Формулы со ссылками в стиле R1C1 можно вставлять в ячейки рабочей книги Excel, в которой по умолчанию установлены ссылки в стиле A1. Вставленные ссылки в стиле R1C1 будут автоматически преобразованы в ссылки в стиле A1.
Примеры вставки формул суммирования со ссылками в стиле R1C1 в ячейку F1 (для той же таблицы):
Пример вставки формул суммирования со ссылками в стиле R1C1 в диапазон F1:F10:
Так как формулы с относительными ссылками и относительными по строкам ссылками в стиле R1C1 для всех ячеек столбца F одинаковы, их можно вставить сразу, без использования цикла, во весь диапазон.
19 комментариев для “VBA Excel. Вставка формулы в ячейку”
Доброго времени суток.
Кто-нибудь подскажет, как написать в vba excel вот такую формулу: =»пример текста » & D1 в ячейку, где «пример текста » и D1 должна быть выражена в виде переменных. В итоге в ячейке должно отобразиться: пример текста 50 при условии, что d1=50
Привет, Nik!
Записываем формулу в ячейку «A1» , собрав ее из переменных:
Спасибо большое! Совсем из вида упустил, что можно применить Chr(34).
Ещё один вопрос, почему абсолютная ссылка получается =»Пример текста «&$D$1 , как сделать, что бы была относительная =»Пример текста «&D1 ?
Ещё раз большое спасибо за оперативность.
Здравствуйте. Помогите , пожалуйста. Возникает такая проблема: после замены части формулы с помощью функции Replace,значение в ячейке воспринимается как текст, а не как формула.
Команды
не помогли)). При этом, если подобную замену делать штатным экселевским Заменить, то полученный результат воспринимается как формула и вычисляется сразу.
Здравствуйте, Сусанна!
У меня работает так:
Огромное спасибо) В понедельник приду на работу, и обязательно попробую Ваш вариант.
Добрый вечер. Мне нужно использовать математические операции, опираясь только на переменные. Например:
Cells(i, SOH).Formula = (Cells(i, Stock_rep_date) + Cells(i, Consig_Stock_rep_date)) / 1
Но в ячейках получаются сами значения, а нужна формула с ссылками на ячейки Cells.
Здравствуйте, Дмитрий!
Cells(i, SOH).Formula = «=(» & Cells(i, Stock_rep_date).Address & «+» & Cells(i, Consig_Stock_rep_date).Address & «)/1»
Здравствуйте, Евгений!
Можете помочь?
Дано:
1. В ячейках D1 и D2 некие текстовые данные, которые необходимо объединить в ячейку D3
Range(«D3»).FormulaR1C1 = «=R[-2]C&R[-1]C»
2. Потом в Ячейку D4 получившийся результат вставить как значение
Range(«D3»).Copy
Range(«D4»).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
3. И в ячейке D4 между данными вставить перенос на вторую строку. К примеру:
Range(«C4»).FormulaR1C1 = «Видеокарта» & Chr(10) & «GTX 3090») .
Но проблема в том, что данные неизвестны и могут меняться.
А объединить первый макрос с третьим у меня не получается.
Подскажите как можно одним макросом объединить данные двух ячеек сразу с переносом данных второй ячейки во вторую строку ячейки.
Здравствуйте!
Не совсем понял, что нужно, поэтому привожу пример, как объединить текст из двух ячеек (D1 и D2) в одну строку и как — в две:
Источник
Insert formula in excel with vba
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
Here is my problème :
In my Excel worksheet cell, I have a formula :
=»Table of Personal»&» «&»»&+C2&»year»&» in»&» «&+Zveno_Name
I don’t know how to insert this formula from my VBA code
Anyone knows how to do it?
Thanks in advanced
Answers
The formula itself can be simplified to
=»Table of Personal «&C2&» year in «&Zveno_Name
To create this formula in VBA, you can use
Note that the double quotes » within the formula have been doubled to «». This is necessary because the entire formula is enclosed in double quotes.
Regards, Hans Vogelaar
also a very easy for newbies to learn how to insert formula in VBA form is by «recording the macro».
Under Developper tab (2010)> Record Macro > then do the action.
You will notice all selected cell will be recorded. ALT + F11, you will find Modules folder > module one. You will see that the formula is recorded there.
Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or «Mark as Answer» if it solves your question. This will help to contribute to the forum.
- Proposed as answer by Asadulla Javed Editor Thursday, October 25, 2012 6:41 AM
- Marked as answer by Quist Zhang Thursday, November 1, 2012 6:28 AM
The formula itself can be simplified to
=»Table of Personal «&C2&» year in «&Zveno_Name
To create this formula in VBA, you can use
Note that the double quotes » within the formula have been doubled to «». This is necessary because the entire formula is enclosed in double quotes.
Regards, Hans Vogelaar
also a very easy for newbies to learn how to insert formula in VBA form is by «recording the macro».
Under Developper tab (2010)> Record Macro > then do the action.
You will notice all selected cell will be recorded. ALT + F11, you will find Modules folder > module one. You will see that the formula is recorded there.
Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or «Mark as Answer» if it solves your question. This will help to contribute to the forum.
- Proposed as answer by Asadulla Javed Editor Thursday, October 25, 2012 6:41 AM
- Marked as answer by Quist Zhang Thursday, November 1, 2012 6:28 AM
Inserting formulas into a cell using VBA was quite strange to me as well, due to the need to write the formula in a way it will work in excel having in mind the local regional settings as string.
Is there «.formula» (something) that will store the formula of i.e.:
ActiveCell.formula = WorksheetFunction.VLookup(ActiveCell.Offset(0, -1).Value, Range(«A2:B2», _ Range(«A2:B2»).End(xlDown)), 2, False)
instead of storing the value?
I was able to write a macro that get’s the job done, however it requires creating additional variables that will be part of the formula as a string. For the unknown part of current row and end of source table. In the example below it’s somehow acceptable, but if part of a macro that uses a lot of functions and formulas to build a bit more complex report from somewhat more raw data it will be quite a pain to use such an approach. Any ideas how to get rid of lastRow & curRow variables and use the normal VBA WorksheetFunction syntax to get the job done?
Sub FormulaSaveTest()
Dim lastRow As Long
Dim curRow As Long
Источник
Insert formula in excel with vba
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
Here is my problème :
In my Excel worksheet cell, I have a formula :
=»Table of Personal»&» «&»»&+C2&»year»&» in»&» «&+Zveno_Name
I don’t know how to insert this formula from my VBA code
Anyone knows how to do it?
Thanks in advanced
Answers
The formula itself can be simplified to
=»Table of Personal «&C2&» year in «&Zveno_Name
To create this formula in VBA, you can use
Note that the double quotes » within the formula have been doubled to «». This is necessary because the entire formula is enclosed in double quotes.
Regards, Hans Vogelaar
also a very easy for newbies to learn how to insert formula in VBA form is by «recording the macro».
Under Developper tab (2010)> Record Macro > then do the action.
You will notice all selected cell will be recorded. ALT + F11, you will find Modules folder > module one. You will see that the formula is recorded there.
Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or «Mark as Answer» if it solves your question. This will help to contribute to the forum.
- Proposed as answer by Asadulla Javed Editor Thursday, October 25, 2012 6:41 AM
- Marked as answer by Quist Zhang Thursday, November 1, 2012 6:28 AM
The formula itself can be simplified to
=»Table of Personal «&C2&» year in «&Zveno_Name
To create this formula in VBA, you can use
Note that the double quotes » within the formula have been doubled to «». This is necessary because the entire formula is enclosed in double quotes.
Regards, Hans Vogelaar
also a very easy for newbies to learn how to insert formula in VBA form is by «recording the macro».
Under Developper tab (2010)> Record Macro > then do the action.
You will notice all selected cell will be recorded. ALT + F11, you will find Modules folder > module one. You will see that the formula is recorded there.
Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or «Mark as Answer» if it solves your question. This will help to contribute to the forum.
- Proposed as answer by Asadulla Javed Editor Thursday, October 25, 2012 6:41 AM
- Marked as answer by Quist Zhang Thursday, November 1, 2012 6:28 AM
Inserting formulas into a cell using VBA was quite strange to me as well, due to the need to write the formula in a way it will work in excel having in mind the local regional settings as string.
Is there «.formula» (something) that will store the formula of i.e.:
ActiveCell.formula = WorksheetFunction.VLookup(ActiveCell.Offset(0, -1).Value, Range(«A2:B2», _ Range(«A2:B2»).End(xlDown)), 2, False)
instead of storing the value?
I was able to write a macro that get’s the job done, however it requires creating additional variables that will be part of the formula as a string. For the unknown part of current row and end of source table. In the example below it’s somehow acceptable, but if part of a macro that uses a lot of functions and formulas to build a bit more complex report from somewhat more raw data it will be quite a pain to use such an approach. Any ideas how to get rid of lastRow & curRow variables and use the normal VBA WorksheetFunction syntax to get the job done?
Sub FormulaSaveTest()
Dim lastRow As Long
Dim curRow As Long
Источник
Bottom line: Learn 3 tips for writing and creating formulas in your VBA macros with this article and video.
Skill level: Intermediate
Video Tutorial
Download the File
Download the Excel file to follow along with the video.
Automate Formula Writing
Writing formulas can be one of the most time consuming parts of your weekly or monthly Excel task. If you’re working on automating that process with a macro, then you can have VBA write the formula and input it into the cells for you.
Writing formulas in VBA can be a bit tricky at first, so here are 3 tips to help save time and make the process easier.
Tip #1: The Formula Property
The Formula property is a member of the Range object in VBA. We can use it to set/create a formula for a single cell or range of cells.
There are a few requirements for the value of the formula that we set with the Formula property:
- The formula is a string of text that is wrapped in quotation marks. The value of the formula must start and end in quotation marks.
- The formula string must start with an equal sign = after the first quotation mark.
Here is a simple example of a formula in a macro.
Sub Formula_Property()
'Formula is a string of text wrapped in quotation marks
'Starts with an = sign
Range("B10").Formula = "=SUM(B4:B9)"
End Sub
The Formula property can also be used to read an existing formula in a cell.
Tip #2: Use the Macro Recorder
When your formulas are more complex or contain special characters, they can be more challenging to write in VBA. Fortunately we can use the macro recorder to create the code for us.
Here are the steps to creating the formula property code with the macro recorder.
- Turn on the macro recorder (Developer tab > Record Macro)
- Type your formula or edit an existing formula.
- Press Enter to enter the formula.
- The code is created in the macro.
If your formula contains quotation marks or ampersand symbols, the macro recorder will account for this. It creates all the sub-strings and wraps everything in quotes properly. Here is an example.
Sub Macro10()
'Use the macro recorder to create code for complex formulas with
'special characters and relative references
ActiveCell.FormulaR1C1 = "=""Total Sales: "" & TEXT(R[-5]C,""$#,###"")"
End Sub
Tip #3: R1C1 Style Formula Notation
If you use the macro recorder for formulas, you will notices that it creates code with the FormulaR1C1 property.
R1C1 style notation allows us to create both relative (A1), absolute ($A$1), and mixed ($A1, A$1) references in our macro code.
R1C1 stands for Rows and Columns.
Relative References
For relative references we specify the number of rows and columns we want to offset from the cell that the formula is in. The number of rows and columns are referenced in square brackets.
The following would create a reference to a cell that is 3 rows above and 2 rows to the right of the cell that contains the formula.
R[-3]C[2]
Negative numbers go up rows and columns to the left.
Positive numbers go down rows and columns to the right.
Absolute References
We can also use R1C1 notation for absolute references. This would typically look like $A$2.
For absolute references we do NOT use the square brackets. The following would create a direct reference to cell $A$2, row 2 column 1
R2C1
Mixed References
with mixed references we add the square brackets for either the row or column reference, and no brackets for the other reference. The following formula in cell B2 would create this reference to A$2, where the row is absolute and the column is relative.
R2C[-1]
When creating mixed references, the relative row or column number will depend on what cell the formula is in.
It’s easiest to just use the macro recorder to figure these out.
FormulaR1C1 Property versus Formula Property
The FormulaR1C1 property reads the R1C1 notation and creates the proper references in the cells. If you use the regular Formula property with R1C1 notation, then VBA will attempt to put those letters in the formula, and it will likely result in a formula error.
Therefore, use the Formula property when your code contains cell references ($A$1), the FormulaR1C1 property when you need relative references that are applied to multiple cells or dependent on where the formula is entered.
If your spreadsheet changes based on conditions outside your control, like new columns or rows of data are imported from the data source, then relative references and R1C1 style notation will probably be best.
I hope those tips help. Please leave a comment below with questions or suggestions.