Vba excel if formula in cell

  • #1

Hi,

I am trying to search through a range of cells, if any cell contains formula. If the cell contains formula, it has to pop-up «Yes».

But I am getting Error as Object Required. Please help.

here is my code:

VBA Code:

Sub chkform()
Rng = Range("R8:R16")
For Each cell In Rng
    If cell.HasFormula = True Then
        MsgBox "Yes"
    End If
Next cell
End Sub

Why does 9 mean SUM in SUBTOTAL?

It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.

  • #2

VBA Code:

Option Explicit

Sub chkform()
Dim cell As Range
Dim rng As Range
Set rng = Range("R8:R16")
For Each cell In rng
    If cell.HasFormula = True Then
        MsgBox "Yes"
    End If
Next cell
End Sub

  • #3

VBA Code:

Option Explicit

Sub chkform()
Dim cell As Range
Dim rng As Range
Set rng = Range("R8:R16")
For Each cell In rng
    If cell.HasFormula = True Then
        MsgBox "Yes"
    End If
Next cell
End Sub

Awesome…. Its working fine… Thank you so much

  • #4

Hi, I have one more question with respect to «For each cell».

How to copy an entire row from this loop and paste it in another sheet.

Thanks

  • #5

Just wanted to update this question, maybe I am not clear.

I am using the loop :

VBA Code:

For Each cell In rng
    If cell.HasFormula = True Then
        MsgBox "Yes"
    End If
Next cell

In this loop, if I want to capture the entire row where «cell.HasFormula = True», how to get that?

Please help.

Thanks,

  • #6

Something like?…..

VBA Code:

Sub chkform()
Dim cell As Range, rng As Range
Set rng = Range("R8:R16")

For Each cell In rng
    If cell.HasFormula = True Then cell.EntireRow.Interior.ColorIndex = 6
Next cell
End Sub

  • #7

Hi

VBA Code:

Sub chkform()
    Dim cell As Range
    Dim rng As Range
    Dim r As Range
    Set rng = Range("R8:R16")
    For Each cell In rng
        If cell.HasFormula = True Then
            If Not r Is Nothing Then
                Set r = Union(r, cell.EntireRow)
            Else: Set r = cell.EntireRow
            End If
        End If
    Next cell
    r.Select
End Sub

Peter_SSs

James006

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.

Table of contents
How to add formula to cell using VBA
Add formula to cell and fill down using VBA
Add sum formula to cell using VBA
How to add If formula to cell using VBA
Add formula to cell with quotes using VBA
Add Vlookup formula to cell using VBA

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.

Add formula to first cell

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

=B2+C2

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.

Sub AddFormula_Method1()

     Dim WS As Worksheet

     Set WS = Worksheets(«Sheet1»)

     WS.Range(«D2»).Formula = «=B2+C2»

End Sub

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

Sub AddFormula_Method2()

    Dim WS As Worksheet

    Set WS = Worksheets(«Sheet1»)

    WS.Range(«D2»).Value = «=B2+C2»

End Sub

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.

Sub AddFormula_Method3A()

    Dim WS As Worksheet

    Set WS = Worksheets(«Sheet1»)

    WS.Range(«D2»).FormulaR1C1 = «=R2C2+R2C3»

End Sub

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.

Sub AddFormula_Method3B()

    Dim WS As Worksheet

    Set WS = Worksheets(«Sheet1»)

    WS.Range(«D2»).FormulaR1C1 = «=RC[-2]+RC[-1]»

End Sub

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.

Sub AddFormula_Method3C()

     Dim WS As Worksheet

     Set WS = Worksheets(«Sheet2»)

     WS.Range(«C5»).FormulaR1C1 = «=RC[-1]+RC[-1]*R2C2»

End Sub

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”

Sub AddFormula_Method1_1000Rows()

End Sub

Then we need an additional variable for the For Next statement

Dim WS As Worksheet
Dim i As Integer

Next, assign the worksheet to WS variable

Set WS = Worksheets(«Sheet1»)

Now we can add the For Next statement like this.

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

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.

Sub AddFormula_Method1_1000Rows()

     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

End Sub

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.

Sub AddFormula_Method3A_1000Rows()

     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

End Sub

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

Sub AddFormula_Method3B_1000Rows()

     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

End Sub

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.

=SUM(D2:D15)

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

First let’s declare a few variables.

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

Assign the worksheet to the variable.

Set WS = Worksheets(«Sheet3»)

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

StartingRow = 2
EndingRow = 1

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

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

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

Sub SumFormula()

     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 & «)»

End Sub

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.

=IF(B2>=40,»Pass»,»Fail»)

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”

Sub AddIfFormula()

End Sub

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.

Sub AddIfFormula_Method1()

     Dim WS As Worksheet

     Set WS = Worksheets(«Sheet4»)

     WS.Range(«C2»).Formula = «=IF(B2>=40,»»Pass»»,»»Fail»»)»

End Sub

Sub AddIfFormula_Method2()

     Dim WS As Worksheet

     Set WS = Worksheets(«Sheet4»)

     WS.Range(«C2»).Formula = «=IF(B2>=40,» & Chr(34) & «Pass» & Chr(34) & «,» & Chr(34) & «Fail» & Chr(34) & «)»

End Sub

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.

=VLOOKUP(Sheet5!C2,Sheet4!A2:C200,3,FALSE)

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

Sub AddVlookupFormula()

     Dim WS As Worksheet

     Set WS = Worksheets(«Sheet5»)

     WS.Range(«C3»).Formula = «=VLOOKUP(Sheet5!C2,Sheet4!A2:C200,3,FALSE)»

End Sub

Completed Vlookup example

Is it possible to conditionally format a cell if the cell contains formula (to alert myself and other users when updating the cell)?

toryan's user avatar

toryan

9217 silver badges19 bronze badges

asked Oct 31, 2011 at 9:51

wilson's user avatar

2

There is a very simple way to do this, tested in Excel 2016.

Highlight your range you wish this to apply to, let’s say from A3:W20. Go into conditional formatting and select NEW RULE | USE A FORMULA TO DETERMINE WHICH CELLS TO FORMAT.

Put in =isformula(A3) and pick the format you want to apply.

A3 is obviously a reference to the first cell in your range but this formatting then applies to all. The result is that within your range, any cell that is a formula is conditionally formatted.

tinlyx's user avatar

tinlyx

1,4406 gold badges26 silver badges42 bronze badges

answered Apr 17, 2018 at 7:39

Joe Dog's user avatar

Joe DogJoe Dog

1461 silver badge2 bronze badges

2

Building on brettdj’s answer, because I found the linked article quite difficult to follow:

  1. Create a new Conditional Formatting rule and select Use a formula to determine which cells to format
  2. Insert the following formula: =ISFORMULA(INDIRECT("rc",FALSE))
  3. If you want the rule to apply to the whole worksheet, $1:$1048576 as the range to apply to. Otherwise, you can enter any range.

The formula INDIRECT("rc",FALSE) returns the reference of the current cell. If I ever use this in a sheet, I create a Defined Name called something like ThisCell and use that in the formula, just in case I ever come back years later and think «what the hell is this for?».

answered Mar 27, 2014 at 23:48

toryan's user avatar

toryantoryan

9217 silver badges19 bronze badges

2

You can try these:

VBA

Create a custom function with the following code:

Function IsFormula(ByVal Ref As Range) As Variant
    If Ref.Cells.Count > 1 Then
        IsFormula = CVErr(xlErrNA)
    Else
        IsFormula = Ref.HasFormula
    End If
End Function

Example:

To check if any cells in column A have any formulas:

  1. Highlight column A
  2. Go to Conditional Formatting > New Rule > Use a formula to determine which cells to format
  3. Use the ff. formula: =IsFormula(A1)

Non-VBA

  1. Press F5 or Ctrl + G
  2. Click Special.
  3. Choose Formulas and click OK. This highlights all cells in the worksheet that contains formulas.
  4. Set up the format you’d like to use.
    Or
    Go to Cell Styles (under the Home tab) and pick a style that you want to associate with formula-containing cells. To change the look-and-feel, right-click on the style that you selected and click Modify. All cells given this style will automatically be updated.

Community's user avatar

answered Oct 31, 2011 at 10:39

Ellesa's user avatar

EllesaEllesa

10.8k2 gold badges38 silver badges52 bronze badges

1

The newer help sites recommend a User-Defined Function:

Function IsFormula(cell) as boolean 
  IsFormula = cell.HasFormula
End Function

Then use that function as your condition

And in fact, Excel 2013 and later has IsFormula as a standard function.

answered Oct 1, 2015 at 12:30

Carl Witthoft's user avatar

You can also use conditional formatting:

  1. Select the range of cells you want to apply your conditional formatting to
  2. In Home -> Conditional formatting -> New rule: Use a formula to detect which cell to format
  3. In Format values when this formula is true put: =HasNoFormula
  4. Select the format you want

Tested using Excel 2010.

Tim's user avatar

Tim

2,1221 gold badge22 silver badges27 bronze badges

answered Oct 16, 2013 at 12:39

Deconinck Florian's user avatar

2

Excel VBA — How to Know if the Cell Has Formula

To get the cell that contains formula couple of useful properties are available in Excel VBA

1. HasFormula
2. SpecialCells(xlCellTypeFormulas)

HasFormula will give True or False depending on the availabiliy of formulas

whereas

SpecialCells(xlCellTypeFormulas) can be used to select all the cells that contain formula

cells.SpecialCells(xlCellTypeFormulas).Select

or Set rng = cells.SpecialCells(xlCellTypeFormulas)

For each Cll in Rng

‘ Each cell containing formula

Next

free search engine website submission top optimization
Cheers
Shasur

StumbleUpon

Related Posts Plugin for WordPress, Blogger...

Bottom line: Learn 3 tips for writing and creating formulas in your VBA macros with this article and video.

Skill level: Intermediate

Video Tutorial

Watch on YouTube & Subscribe to our Channel

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:

  1. 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.
  2. 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.

Create Formula VBA code with the Macro Recorder

Here are the steps to creating the formula property code with the macro recorder.

  1. Turn on the macro recorder (Developer tab > Record Macro)
  2. Type your formula or edit an existing formula.
  3. Press Enter to enter the formula.
  4. 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.

Like this post? Please share to your friends:
  • Vba excel if exists file
  • Vba excel if elseif
  • Vba excel find and select
  • Vba excel find all cells
  • Vba excel filtered rows