Vba как вставить формулу в ячейку excel

от admin

Excel-VBA Solutions

Want to become an expert in VBA? So this is the right place for you. This blog mainly focus on teaching how to apply Visual Basic for Microsoft Excel. So improve the functionality of your excel workbooks with the aid of this blog. Also ask any questions you have regarding MS Excel and applying VBA. We are happy to assist you.

Pages

  • POSTS LIST
  • CONTACT
  • PRODUCTS
  • PRIVACY POLICY

How to Add a Formula to a Cell Using VBA

In this lesson you can learn how to add a formula to a cell using vba. There are several ways to insert formulas to cells automatically. We can use properties like Formula, Value and FormulaR1C1 of the Range object. This post explains five different ways to add formulas to cells.

We use formulas to calculate various things in Excel. Sometimes you may need to enter the same formula to hundreds or thousands of rows or columns only changing the row numbers or columns. For an example let’s consider this sample Excel sheet.

In this Excel sheet I have added a very simple formula to the D2 cell.

So what if we want to add similar formulas for all the rows in column D. So the D3 cell will have the formula as =B3+C3 and D4 will have the formula as =B4+D4 and so on. Luckily we don’t need to type the formulas manually in all rows. There is a much easier way to do this. First select the cell containing the formula. Then take the cursor to the bottom right corner of the cell. Mouse pointer will change to a + sign. Then left click and drag the mouse until the end of the rows.

However if you want to add the same formula again and again for lots of Excel sheets then you can use a VBA macro to speed up the process. First let’s look at how to add a formula to one cell using vba.

How to add formula to cell using VBA

Lets see how we can enter above simple formula(=B2+C2) to cell D2 using VBA

In this method we are going to use the Formula property of the Range object.

Dim WS As Worksheet

Set WS = Worksheets(«Sheet1»)

We can also use the Value property of the Range object to add a formula to a cell.

Dim WS As Worksheet

Set WS = Worksheets(«Sheet1»)

Next method is to use the FormulaR1C1 property of the Range object. There are few different ways to use FormulaR1C1 property. We can use absolute reference, relative reference or use both types of references inside the same formula.

In the absolute reference method cells are referred to using numbers. Excel sheets have numbers for each row. So you should think similarly for columns. So column A is number 1. Column B is number 2 etc. Then when writing the formula use R before the row number and C before the column number. So the cell A1 is referred to by R1C1. A2 is referred to by R2C1. B3 is referred to by R3C2 etc.

This is how you can use the absolute reference.

Dim WS As Worksheet

Set WS = Worksheets(«Sheet1»)

If you use the absolute reference, the formula will be added like this.

Absolute reference

If you use the manual drag method explained above to fill down other rows, then the same formula will be copied to all the rows.

Same formula is copied to all the rows

In Majority cases this is not how you want to fill down the formula. However this won’t happen in the relative method. In the relative method, cells are given numbers relative to the cell where the formula is entered. You should use negative numbers when referring to the cells in upward direction or left. Also the numbers should be placed within the square brackets. And you can omit [0] when referring to cells on the same row or column. So you can use RC[-2] instead of R[0]C[-2]. The macro recorder also generates relative reference type code, if you enter a formula to a cell while enabling the macro recorder.

Below example shows how to put formula =B2+C2 in D2 cell using relative reference method.

Dim WS As Worksheet

Set WS = Worksheets(«Sheet1»)

Relative reference

Now use the drag method to fill down all the rows.

Formulas are changed according to the row number

You can see that the formulas are changed according to the row numbers.

Also you can use both relative and absolute references in the same formula. Here is a typical example where you need a formula with both reference types.

Example sheet to use both relative and absolute references

We can add the formula to calculate Total Amount like this.

Dim WS As Worksheet

Set WS = Worksheets(«Sheet2»)

Add formula using both absolute and relative reference

In this formula we have a absolute reference after the * symbol. So when we fill down the formula using the drag method that part will remain the same for all the rows. Hence we will get correct results for all the rows.

Fill down formula using drag method - relative and absolute reference

Add formula to cell and fill down using VBA

So now you’ve learnt various methods to add a formula to a cell. Next let’s look at how to fill down the other rows with the added formula using VBA.

Thousand rows example

Assume we have to calculate cell D2 value using =B2+C2 formula and fill down up to 1000 rows. First let’s see how we can modify the first method to do this. Let’s name this subroutine as “AddFormula_Method1_1000Rows”

Then we need an additional variable for the For Next statement

Next, assign the worksheet to WS variable

Now we can add the For Next statement like this.

Here I have used «D» & i instead of D2 and «=B» & i & «+C» & i instead of «=B2+C2». So the formula keeps changing like =B3+C3, =B4+C4, =B5+C5 etc. when iterated through the For Next loop.

Below is the full code of the subroutine.

Dim WS As Worksheet
Dim i As Integer

Set WS = Worksheets(«Sheet1»)

For i = 2 To 1000
WS.Range(«D» & i).Formula = «=B» & i & «+C» & i
Next i

So that’s how you can use VBA to add formulas to cells with variables.

Next example shows how to modify the absolute reference type of FormulaR1C1 method to add formulas upto 1000 rows.

Dim WS As Worksheet
Dim i As Integer

Set WS = Worksheets(«Sheet1»)

For i = 2 To 1000
WS.Range(«D» & i).FormulaR1C1 = «=R» & i & «C2+R» & i & «C3»
Next i

You don’t need to do any change to the formula section when modifying the relative reference type of the FormulaR1C1 method.

Dim WS As Worksheet
Dim i As Integer

Set WS = Worksheets(«Sheet1»)

For i = 2 To 1000
WS.Range(«D» & i).FormulaR1C1 = «=RC[-2]+RC[-1]»
Next i

Use similar techniques to modify other two types of subroutines to add formulas for multiple rows. Now you know how to add formulas to cells with a variable. Next let’s look at how to add formulas with some inbuilt functions using VBA.

How to add sum formula to a cell using VBA

Sample sheet for Sum formula example

Suppose we want the total of column D in the D16 cell. So this is the formula we need to create.

Now let’s see how to add this using VBA. Let’s name this subroutine as SumFormula.

First let’s declare a few variables.

Assign the worksheet to the variable.

Assign the starting row and the ending row to relevant variables.

Then the final step is to create the formula with the above variables.

Below is the full code to add the Sum formula using VBA.

Dim WS As Worksheet
Dim StartingRow As Long
Dim EndingRow As Long

Set WS = Worksheets(«Sheet3»)
StartingRow = 2
EndingRow = 15

WS.Range(«D16»).Formula = «=SUM(D» & StartingRow & «:D» & EndingRow & «)»

How to add If Formula to a cell using VBA

If function is a very popular inbuilt worksheet function available in Microsoft Excel. This function has 3 arguments. Two of them are optional.

Arguments of the If formula

Now let’s see how to add a If formula to a cell using VBA. Here is a typical example where we need a simple If function.

Sample Excel sheet for If formula example

This is the results of students on an examination. Here we have names of students in column A and their marks in column B. Students should get “Pass” if he/she has marks equal or higher than 40. If marks are less than 40 then Excel should show the “Fail” in column C. We can simply obtain this result by adding an If function to column C. Below is the function we need in the C2 cell.

Now let’s look at how to add this If Formula to a C2 cell using VBA. Once you know how to add it then you can use the For Next statement to fill the rest of the rows like we did above. We discussed a few different ways to add formulas to a range object using VBA. For this particular example I’m going to use the Formula property of the Range object.

So now let’s see how we can develop this macro. Let’s name this subroutine as “AddIfFormula”

However we can’t simply add this If formula using the Formula property like we did before. Because this If formula has quotes inside it. So if we try to add the formula to the cell with quotes, then we get a syntax error.

If we add the formula to the cell with quotes then we will get syntax error

Add formula to cell with quotes

There are two ways to add the formula to a cell with quotes.

Dim WS As Worksheet

Set WS = Worksheets(«Sheet4»)

Dim WS As Worksheet

Set WS = Worksheets(«Sheet4»)

WS.Range(«C2»).Formula & Chr(34) & «Pass» & Chr(34) & «,» & Chr(34) & «Fail» & Chr(34) & «)»

Add vlookup formula to cell using VBA

Finally I will show you how to add a vlookup formula to a cell using VBA. So I created a very simple example where we can use a Vlookup function. Assume we have this section in the Sheet5 of the same workbook.

Sample Excel sheet for Vlookup formula example

So here when we change the name of the student in the C2 cell, his/her pass or fail status should automatically be shown in the C3 cell. If the original data(data we used in the above “If formula” example) is listed in the Sheet4 then we can write a Vlookup formula for the C3 cell like this.

Читать:
Почему php не работает в html

We can use the Formula property of the Range object to add this Vlookup formula to the C3 using VBA.

Excel VBA Formulas – The Ultimate Guide

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.

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:

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!

automacro

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 (“”):

vba formula quotations

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-free-addin

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 Formulas

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.

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» by VBA:

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

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).

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.

  • 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

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

N negative can only be used in relative notation.

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

VBA WorksheetFunction

Excel formulas can also be accessed by object WorksheetFunction methods.

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.

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

VBA Excel. Вставка формулы в ячейку

В качестве примера будем использовать диапазон 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) в одну строку и как — в две:

Похожие статьи