Excel vba получить формулу

Get a formula from a cell using VBA in Excel.

This method returns the actual formula instead of the output value.

Get the Formula of a Cell into a Macro

We use the Formula property for this.

To get the formula in cell A1, type this in a macro:

Range("A1").Formula

5f4c85a8b3d434417958fa3c838b85a7.jpg

I will put MsgBox in front of this line of code so we can see the output in Excel:

MsgBox Range("A1").Formula

Go back to Excel and run it on a cell that has a date and this is the result:

9fd379c46222835b5be956c846f42cc6.jpg

In cell A1, you can see the actual visible output, which is the date, and in the message box pop-up you can see the formula that was used to create the output.

Using Formula in VBA means that the macro will get the formula that we see in the message box.

Notes

This is pretty straightforward, if you want to get the value of a cell that is easy and you can read about it in the link.

Download the attached workbook to see this example in Excel.


Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons
50+ Hours of Instruction
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Similar Content on TeachExcel

Get Text from Comments in Excel Including the Author of the Comment — UDF

Macro: Output all text from a cell comment, including comment author, with this UDF in Excel. Thi…

Loop through a Range of Cells in Excel VBA/Macros

Tutorial: How to use VBA/Macros to iterate through each cell in a range, either a row, a column, or …

Limit the Total Amount a User Can Enter into a Range of Cells in Excel

Tutorial: How to limit the amount that a user can enter into a range of cells in Excel.  This works…

Me Keyword in Excel Macros & VBA

Tutorial: The Me keyword in Excel VBA allows you to refer to either the current worksheet, workbook,…

Select Ranges of Cells in Excel using Macros and VBA

Tutorial: This Excel VBA tutorial focuses specifically on selecting ranges of cells in Excel.  This…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Excel VBA Course

Excel VBA Course — From Beginner to Expert

200+ Video Lessons

50+ Hours of Video

200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Содержание

  1. Excel VBA Formulas – The Ultimate Guide
  2. Formulas in VBA
  3. Macro Recorder and Cell Formulas
  4. VBA FormulaR1C1 Property
  5. Absolute References
  6. Relative References
  7. Mixed References
  8. VBA Coding Made Easy
  9. VBA Formula Property
  10. VBA Formula Tips
  11. Formula With Variable
  12. Formula Quotations
  13. Assign Cell Formula to String Variable
  14. Different Ways to Add Formulas to a Cell
  15. Refresh Formulas
  16. VBA Code Examples Add-in
  17. Свойство Range.Formula (Excel)
  18. Синтаксис
  19. Замечания
  20. См. также
  21. Пример
  22. Поддержка и обратная связь
  23. Свойство Range.FormulaR1C1 (Excel)
  24. Синтаксис
  25. Примечания
  26. Пример
  27. Поддержка и обратная связь
  28. Формула и Формула 2
  29. Перевод с Range.Formula на Range.Formula2
  30. Перевод с Range.Formula2 на Range.Formula
  31. Рекомендация
  32. Заметки
  33. Поддержка и обратная связь
  34. VBA Excel. Вставка формулы в ячейку
  35. Свойство Range.FormulaLocal
  36. Свойство Range.FormulaR1C1Local
  37. 19 комментариев для “VBA Excel. Вставка формулы в ячейку”

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:

  1. Directly Assign Formula
  2. Define a String Variable Containing the Formula
  3. 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.

Источник

Свойство Range.Formula (Excel)

Возвращает или задает значение Variant , представляющее неявно пересекающуюся формулу объекта в нотации стиля A1.

Синтаксис

expression. Формула

выражение: переменная, представляющая объект Range.

Замечания

В Excel с поддержкой динамических массивов Range.Formula2 заменяет Range.Formula. Range.Formula будет по-прежнему поддерживаться для обеспечения обратной совместимости. Обсуждение динамических массивов и Range.Formula2 можно найти здесь.

См. также

Свойство Range.Formula2

Это свойство недоступно для источников данных OLAP.

Если ячейка содержит константу, это свойство возвращает константу. Если ячейка пуста, это свойство возвращает пустую строку. Если ячейка содержит формулу, свойство Formula возвращает формулу в виде строки в том же формате, который будет отображаться в строке формул (включая знак равенства ( = )).

Если для ячейки задано значение или формула даты, Microsoft Excel проверяет, что ячейка уже отформатирована с помощью одного из форматов чисел даты или времени. В противном случае Excel изменит числовой формат на короткий формат даты по умолчанию.

Если диапазон состоит из одного или двух измерений, можно установить формулу для массива Visual Basic с теми же размерами. Аналогично, можно поместить формулу в массив Visual Basic.

Формулы, заданные с помощью Range.Formula, могут вызывать неявное пересечение.

Если задать формулу для диапазона с несколькими ячейками, все ячейки в диапазоне заполняются формулой.

Пример

В следующем примере кода задается формула для ячейки A1 на Листе1.

В следующем примере кода задается формула ячейки A1 на листе 1 для отображения текущей даты.

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

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

Источник

Свойство Range.FormulaR1C1 (Excel)

Возвращает или задает формулу для объекта с использованием нотации в стиле R1C1 на языке макроса. Для чтения и записи, Variant.

Синтаксис

выражение. FormulaR1C1

выражение: переменная, представляющая объект Range.

Примечания

Если ячейка содержит константу, это свойство возвращает константу. Если ячейка пуста, свойство возвращает пустую строку. Если ячейка содержит формулу, свойство возвращает формулу в виде строки в том же формате, в котором она будет отображаться в строке формул (включая знак равенства).

Если присвоить значение или формулу ячейки для даты, Microsoft Excel проверяет, отформатирована ли эта ячейка с помощью одного из форматов даты или времени. В противном случае числовой формат изменяется на формат короткой даты по умолчанию.

Если диапазон состоит из одного или двух измерений, можно установить формулу для массива Visual Basic с теми же размерами. Аналогично, можно поместить формулу в массив Visual Basic.

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

Пример

В этом примере задается формула для ячейки B1 на листе Sheet1.

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

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

Источник

Формула и Формула 2

Range.Formula и Range.Formula2 — это два разных способа представления логики в формуле. Их можно представить на двух диалектах языка формул Excel.

Excel всегда поддерживал два типа вычисления формул: неявное вычисление пересечения («IIE») и вычисление массива («AE»). До появления динамических массивов IIE использовался по умолчанию для формул ячеек, в то время как AE использовался везде (условное форматирование, проверка данных, формулы массива CSE и т. д.).

Основное различие между двумя формами оценки заключается в том, как они ведут себя при передаче многоэлементного диапазона (например, A1:A10) функции, которая ожидала одно значение:

  • IIE выберет ячейку в той же строке или столбце, что и формула. Эта операция называется «неявным пересечением».
  • AE вызывает функцию с каждой ячейкой в диапазоне с несколькими ячейками и возвращает массив результатов. Эта операция называется «лифтинг».

Если range.Formula используется для задания формулы ячейки, для оценки используется IIE.

С появлением Dyanamic Arrays («DA») Excel теперь поддерживает возврат нескольких значений в сетку, и AE теперь используется по умолчанию. Формулы AE можно задать или прочитать с помощью Range.Formula2, который заменяет Range.Formula. Тем не менее, чтобы упростить обратную совместимость, Range.Formula по-прежнему поддерживается и будет продолжать задавать и возвращать формулы IIE. Набор формулы с помощью Range.Formula вызовет неявное пересечение и никогда не может разлиться. Формула, считываемая с помощью Range.Formula, будет по-прежнему молчать о месте неявного пересечения.

Range.Formula фактически сообщает о том, что будет представлено в строке формул в Excel до DA, а Range.Formula2 — формуле, сообщаемой строкой формул в DA Excel.

Excel автоматически преобразуется между этими двумя вариантами формул, поэтому их можно считывать и задавать. Чтобы упростить перевод из Range.Formula (с помощью IIE) в Range.Formula2 (AE), Excel будет указывать, где может происходить неявное пересечение с помощью нового оператора неявного пересечения @. Аналогичным образом, чтобы упростить преобразование из Range.Formula2 (с помощью AE) в Range.Formula (с помощью IIE), Excel удалит операторы @, которые будут выполняться автоматически. Часто между ними нет разницы.

Перевод с Range.Formula на Range.Formula2

В этом примере показан результат настройки Range.Formula, а затем получения Range.Formula2

Запись Range.Formula Чтение Range.Formula2 Заметки
=SQRT(A1) =SQRT(A1) Идентично, так как неявное пересечение не могло произойти
=SQRT(A1:A4) =SQRT(@A1:A4) SQRT ожидает одно значение, но получает многоэлементный диапазон. Это активирует неявное пересечение в IIE, поэтому преобразование в AE вызывает, где может происходить неявное пересечение с помощью оператора @

Перевод с Range.Formula2 на Range.Formula

Формула, заданная с помощью Range.Formula2 в Excel используется AE. При сохранении файла DA Excel проверяет формулы в книге, чтобы определить, будут ли они вычислять одинаковые в AE и IIE. В этом случае excel может сохранить его в виде IIE, чтобы уменьшить количество формул массива, которые можно увидеть в версиях Excel, предшествующих DA. Вы можете проверить, будет ли формула сохранена в файле в виде формулы массива, используя Range.SavedAsArray()

Запись Range.Formula2 Чтение Range.Formula Чтение Range.SavedAsArray Заметки
=SQRT(A1) =SQRT(A1) FALSE SQRT ожидает одно значение, а A1 — одно значение. Поэтому нет различий между IIE и AE. Сохранить как IIE и удалить все @’s
=SQRT(@A1:A4) =SQRT(A1:A4) FALSE SQRT ожидает одно значение, @A1:A4 является одним значением. Поэтому нет различий между IIE и AE. Сохранить как IIE и удалить все @’s
=SQRT(A1:A4) =SQRT(A1:A4) TRUE SQRT ожидает одно значение, A1:A4 — многоэлементный диапазон. IIE и AE могут отличаться, поэтому сохранить как массив
=SQRT(A1:A4)+ SQRT(@A1:A4) =SQRT(A1:A4)+ SQRT(@A1:A4) TRUE Первый SQRT ожидает одно значение, A1:A4 является многоэлементным диапазоном. IIE и AE могут отличаться, поэтому сохранить как массив

Рекомендация

Если используется версия Excel da, следует использовать Range.Formula2 в качестве параметра Range.Formula.

Если используется предварительная и post DA версии Excel, следует продолжать использовать Range.Formula. Если же вы хотите жестко контролировать внешний вид формулы в строке формул пользователей, следует определить, является ли . Формула 2 поддерживается и, если да, используйте . Формула 2 в противном случае используйте . Формула

Заметки

OfficeJS не включает Range.Formula2. Вместо этого Range.Formula всегда сообщает о том, что присутствует в строке формул. Как новый язык с возможностью быстрого развертывания обновлений для надстроек, разработчикам рекомендуется обновлять свои надстройки, если у них возникают проблемы совместимости между AE и IIE.

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

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

Источник

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) в одну строку и как — в две:

Источник

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

This Excel tutorial explains how to show / get formula of a cell using FormulaText Function and VBA.

Search formula of a Cell

Assume that you have the below spreadsheet and you don’t know whether any cells contain a formula.

Excel get formula of a cell 01

Press CTRL + F to open Find and Replace dialog

In the Find what text box, enter equal sign = , then press Find Next button

Excel get formula of a cell 06

Note that if a cell contains equal sign in Cell Text, it will also be searched.

Navigate to Formulas tab > Show Formulas

Excel get formula of a cell 02

Cells contain formulas will display the formulas

Excel get formula of a cell 03

Click the Show Formulas button again to hide the formulas

Excel get formula of a cell 01

Get formula using FormulaText Function

FormulaText Function was introduced Since Excel 2013. FormulaText Function contains only 1 parameter, which is the Range of the Cell you want to show the formula.

Syntax of FormulaText Function

FORMULATEXT(reference)

Example

Using the above example, using FormulaText Function to show the formulas of Cell C1 and C2.

Excel get formula of a cell 04

Get formula of a Cell using VBA

For Excel versions before Excel 2013, as FormulaText is not supported, it is necessary to use VBA to get the Cell formula.

VBA has a Range Property called Formula, which displays the Formula of a Range. We can directly create a custom Function using the Formula Property.

VBA Code

Press ALT+F11  > create a new module > insert the below code

Public Function wGetFormula(rng As Range) As String
    wGetFormula = rng.Formula
End Function

Example

Now go back to worksheet and try the custom function

Excel get formula of a cell 05

Outbound References

https://support.office.com/en-us/article/FORMULATEXT-function-0A786771-54FD-4AE2-96EE-09CDA35439C8


It is possible to use Excel’s ready-to-use formulas through VBA programming. These are properties that can be used with Range or Cells.


VBA Formula

Formula adds predefined Excel formulas to the worksheet. These formulas should be written in English even if you have a language pack installed.

    Range("F2").Formula = "=SUM(B2:C7)"
    Range("F3").Formula = "=SUM($B$2:$C$7)"

VBA Example Formula

Do not worry if the language of your Excel is not English because, as in the example, it will do the translation to the spreadsheet automatically.


Multiple formulas

You can insert multiple formulas at the same time using the Formula property. To do this, simply define a Range object that is larger than a single cell, and the predefined formula will be «dragged» across the range.

«Dragging» manually:

VBA Drag Manual

«Dragging» by VBA:

    Range("D2:D7").Formula = "=SUM(B2:C2)"

VBA Drag Formulas

Another way to perform the same action would be using FillDown method.

    Range("D2").Formula = "=SUM(B2:C2)"
    Range("D2:D7").FillDown

VBA FormulaLocal

FormulaLocal adds predefined Excel formulas to the worksheet. These formulas, however, should be written in the local language of Excel (in the case of Brazil, in Portuguese).

    Range("F2").FormulaLocal = "=SOMA(B2:C7)"

Just as the Formula property, FormulaLocal can be used to make multiple formulas.


VBA FormulaR1C1

FormulaR1C1, as well as Formula and FormulaLocal, also adds pre-defined Excel formulas to the spreadsheet; however, the use of relative and absolute notations have different rules. The formula used must be written in English.

FormulaR1C1 is the way to use Excel’s ready-to-use formulas in VBA by easily integrating them into loops and counting variables.

In the notations:

  • R refers to rows, in the case of vertical displacement
  • C refers to columns, in the case of horizontal displacement
  • N symbolizes an integer that indicates how much must be shifted in number of rows and/or columns
  • Relative notation: Use as reference the Range that called it

The format of the relative formula is: R[N]C[N]:R[N]C[N].

    Range("F2").FormulaR1C1 = "=SUM(R[0]C[-4]:R[5]C[-3])" 'Equals the bottom row
    Range("F2").FormulaR1C1 = "=SUM(RC[-4]:R[5]C[-3])"

When N is omitted, the value 0 is assumed.

In the example, RC[-4]:R[5]C[-3] results in «B2: C7». These cells are obtained by: receding 4 columns to the left RC[-4] from Range(«F2») to obtain «B2»; and 5 lines down and 3 columns to the left R[5]C[-3] from Range(«F2») to obtain «C7».

  • Absolute notation: Use the start of the spreadsheet as a reference

The format of the relative formula is: RNCN:RNCN.

    Range("F2").FormulaR1C1 = "=SUM(R2C2:R7C3)" 'Results in "$B$2:$C$7"

N negative can only be used in relative notation.

The two notations (relative and absolute) can be merged.

    Range("F2").FormulaR1C1 = "=SUM(RC[-4]:R7C3)" 'Results in "B2:$C$7"

VBA WorksheetFunction

Excel formulas can also be accessed by object WorksheetFunction methods.

    Range("F2") = WorksheetFunction.Sum(Range("B2:C7"))

Excel formulas can also be accessed similarly to functions created in VBA.

The formulas present in the WorksheetFunction object are all in English.

One of the great advantages of accessing Excel formulas this way is to be able to use them more easily in the VBA environment.

    MsgBox (WorksheetFunction.Sum(3, 4, 5))
    Expense=4
    MsgBox (WorksheetFunction.Sum(3, 4, 5,-Expense))

To list the available Excel formulas in this format, simply type WorksheetFunction. that automatically an option menu with all formulas will appear:

Intellisense Options



Consolidating Your Learning

Suggested Exercise



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

Понравилась статья? Поделить с друзьями:
  • Excel vba получить текуще время
  • Excel vba получить последнюю строку
  • Excel vba получить номер строки ячейки
  • Excel vba перенести файл
  • Excel vba перемещение файлов