How to Insert Formulas Using VBA

Photo of author
Post By:

Learning How to Insert formulas using VBA can transform your spreadsheet tasks from manual to magical. In this post we’re going to explore a cornerstone skill for automating your Excel workflows, inserting formula using VBA.

This technique not only saves time but also enhances accuracy, ensuring your data is dynamically calculated with precision.

Let’s embark on this journey together, making your first steps in VBA both rewarding and enlightening.

Table of Contents

Introduction

VBA, Excel’s powerful programming language, allows you to automate almost any aspect of your work, including the insertion of formulas into cells.

Understanding how to insert formulas using VBA is crucial for anyone looking to streamline repetitive tasks or implement complex calculations programmatically.

In this guide, I’ll break down the process into manageable steps, ensuring you grasp the basics and can start applying them to your projects.

Benefits of Learning How to Insert Formulas with VBA

Mastering the art of inserting formulas using VBA in Excel offers a transformative boost to your spreadsheet tasks, enhancing your productivity and the quality of your work.

Here are the key benefits of acquiring this skill:

  • Efficiency: Automate the application of the same formula across multiple worksheets, significantly saving time and streamlining your workflow.
  • Accuracy: By using VBA to insert formulas, you minimize the risk of manual entry errors, ensuring your calculations are both consistent and reliable.
  • Flexibility: Gain the ability to dynamically adjust formulas in response to varying conditions or inputs, a feat not achievable with standard Excel formulas.

In essence, learning how to insert formulas using VBA equips you with a powerful tool to enhance the efficiency, accuracy, and flexibility of your Excel projects.

This skill is invaluable for anyone looking to leverage Excel’s full potential, transforming complex tasks into simple, automated processes.

Basic Example: SUM Formula

To get us started with learning how to insert formulas using VBA let’s start with a basic example, how to insert a SUM formula with VBA.

One of the most common formulas used in Excel is the SUM formula. We can use VBA to insert a SUM formula in cell A10, in order to sum the values held in cells A1 to A9:

How to Insert Formulas Using VBA

The first step is to Open the VBA Editor.

You can do this by using the shortcut command of pressing ‘Alt + F11‘, alternatively you can add the Developer tab to Excel and then click on Developer > Visual Basic.

How to Insert Formulas Using VBA

The next step is to Insert a New Module, this is where we can write our Visual Basic code.

To do so Right-click on any of the objects in the Project Explorer window (usually on the left side) and choose ‘Insert‘, then ‘Module‘.

How to Insert Formulas Using VBA

The third step in the process is to write our VBA code in the newly created code window.

In the Code Window add the following VBA code:

The code window should now look like this:

How to Insert Formulas Using VBA

Let’s break down the VBA code to provide a better understanding:

  • Sub InsertSumFormula() starts the definition of a subroutine, a block of code that performs a specific task.
  • Range(“A10”).Formula targets cell A10 and prepares to insert a formula.
  • =SUM(A1:A9)” is the formula being inserted, designed to sum the values from A1 to A9.
  • End Sub tells Excel that the the subroutine is finished.

Remember, comments in code serve as annotations that are not executed by the program but are meant for the programmer or anyone reading the code.

In VBA, comments are marked by an apostrophe (‘) at the beginning of the line.

Everything on the line after the apostrophe is ignored by the VBA interpreter when the code runs, in our example the comment is ‘ This line of code inserts a SUM formula into cell A10 to sum values from A1 to A9.

The final step in the process is to run our new VBA code. The code can be run by pressing F5, or you can click the Play Icon at the top of the Visual Basic Editor:

How to Insert Formulas Using VBA

The end result is we now have a SUM formula in cell A10, all thanks to our newly created VBA code:

How to Insert Formulas Using VBA

Intermediate Example: SUMPRODUCT Formula

A fruit retailer asks us to calculate the weighted average selling price of a seasonal fruit, strawberries, over a year to gauge their pricing strategy effectiveness and adjust future pricing and procurement plans.

In this scenario we have the Month in column A, the Quantiy Sold (Kg) in column B and the Selling Price per Kg in column C.

We will use VBA to calculate the Weighted Average in cell C15:

How to Insert Formulas Using VBA

As with before Open the VBA Editor by pressing ‘Alt + F11‘, or clicking on Developer > Visual Basic.

Then Insert a New Module by Right-clicking on any of the objects in the Project Explorer window (usually on the left side) and choosing ‘Insert‘, then ‘Module‘.

In the Code Window add the following VBA code:

In VBA, when we use the .Formula property to insert a formula into a cell, the formula itself must be written as a string (text enclosed in quotes).

This is because VBA needs to distinguish between the code that it executes and the formula that Excel needs to calculate within a cell.

By placing the formula within quotes, we’re essentially passing it as a piece of text that Excel recognizes and interprets as a formula to be evaluated, rather than as VBA code to be executed.

This method allows VBA to dynamically insert any Excel formula into the cells of a spreadsheet, enabling automation of complex calculations.

Finally, run the code by pressing F5, or by clicking on the Play Icon, and the VBA code will insert the SUMPRODUCT weighted average formula in Cell C15:

How to Insert Formulas Using VBA

With the calculated weighted average selling price of strawberries being $3.77 per kg for the year, this insightful piece of data equips the retailer with a strong foundation for negotiating better wholesale prices.

Advanced Example: Multiple Formulas with an Array

A manufacturing company produces a specific product, and the production cost varies monthly due to changes in raw material prices, labor costs, and operational efficiencies. Additionally, the number of units produced each month varies.

The company aims to identify the month where production was most cost-efficient (i.e., the lowest cost per unit) to understand and replicate these conditions.

To gain insights into our production efficiency, we will use VBA to automate the calculation and analysis of our monthly production costs per unit. The plan involves three main steps:

  • Calculate Monthly Cost Per Unit: We’ll first insert a formula into column D, adjacent to each month’s data, to calculate the cost per unit for each month. This will be done by dividing the total production cost (Column B) by the units produced (Column C) for each month.
  • Identify Lowest Cost Per Unit: Next, we will calculate the lowest cost per unit achieved in any month and display this value in cell C15. This step involves finding the minimum value in the cost per unit calculations we performed in step 1.
  • Determine Month of Lowest Cost Per Unit: Finally, we will use an array formula to identify the month corresponding to the lowest cost per unit, inserting the result into cell C16. This requires matching the lowest cost per unit found in step 2 with its corresponding month and displaying that month’s name.
How to Insert Formulas Using VBA

To get started Open the VBA Editor by pressing ‘Alt + F11‘, or clicking on Developer > Visual Basic.

Then Insert a New Module by Right-clicking on any of the objects in the Project Explorer window (usually on the left side) and choosing ‘Insert‘, then ‘Module‘.

Let’s look at each of these steps in more detail.

  • What It Does: This line calculates the cost per unit for each month. It divides the total production cost (Column B) by the number of units produced (Column C) for each month.
  • How It Works: The .Formula property assigns a formula to a range of cells. Here, it’s used to assign the division formula to each cell in the range D2:D13, effectively applying the formula =B2/C2 through =B13/C13 to each respective cell in column D.
  • What It Does: This code finds the minimum value within the range D2:D13, which contains the calculated costs per unit for each month, and displays this lowest cost per unit in cell C15.
  • How It Works: By using the .Formula property, the MIN function is assigned to cell C15, automatically calculating and displaying the smallest value found in the range D2:D13.
  • What It Does: This line identifies which month corresponds to the lowest cost per unit by using an array formula that combines the INDEX and MATCH functions. The MATCH function locates the position of the lowest cost per unit (found in C15) within the range D2:D13. The INDEX function then uses this position to return the corresponding month’s name from the range A2:A13.
  • How It Works: The .FormulaArray property allows for the insertion of an array formula into a cell. Unlike regular formulas, array formulas can perform multiple calculations on one or more of the items in an array and can return either a single result or multiple results. Array formulas are typically enclosed in curly braces {}, but when entered through VBA, the braces are not required; instead, the .FormulaArray property is used.
  • Why .FormulaArray Is Used: The MATCH function needs to search through an array (the range D2:D13) to find the first occurrence of a specified value (the value in C15). Since this operation involves looking up values within an array and returning a corresponding value from a different array (or range), it’s considered an array operation, necessitating the use of .FormulaArray.

When we run the complete code by pressing F5, or by clicking on the Play Icon, the VBA code will insert all our formulas in the desired cell locations.

How to Insert Formulas Using VBA

Additional Tips

In the journey of enhancing your Excel VBA prowess, from inserting simple SUM formulas to leveraging the power of array formulas for complex analyses.

Here are some additional tips that will further refine your skills and ensure your code is both efficient and adaptable.

  • Dynamic Formula Insertion: In many cases, your datasets won’t have a fixed number of rows. Hardcoding range references in your formulas (like “A1:A9“) can limit the adaptability of your VBA scripts. Utilize VBA to dynamically identify the range extents. For example, determining the last row with data in a particular column allows your formulas to automatically adjust to the size of your dataset. This leads us to the next tip.
  • Use LastRow for Dynamic Ranges: To make your VBA scripts more adaptable, use a method to find the last row of your data before inserting formulas. This can be particularly useful for automatically adjusting the range your formula covers without manually updating the VBA code. For detailed guidance on finding the last row with VBA, refer to my other post titled “How to find the last row with Excel VBA“. This approach ensures that your formulas remain accurate even as new data is added.
  • Leverage Comments Wisely: Use comments not just to explain what a piece of code does, but why it does it. This can be incredibly helpful when revisiting your code or if someone else needs to understand or modify it.
  • Optimize Performance with .FormulaR1C1: When working with formulas in VBA, consider using the .FormulaR1C1 property instead of the .Formula property for more complex calculations. This property allows you to use relative cell references in your formulas, making your code more flexible and easier to maintain, especially when copying formulas across multiple cells or rows.
  • Array Formulas and Their Power: As seen in the advanced example, array formulas inserted via VBA can perform calculations that might otherwise require several steps or even additional helper columns. They’re especially useful for complex operations on multiple data points. However, remember that while powerful, array formulas can also be resource-intensive. Use them judently, particularly in larger spreadsheets, to avoid performance issues.
  • Regularly Back Up Your Workbooks: Before implementing any VBA script, especially ones that modify large portions of your data, ensure you have a backup of your Excel workbook. While VBA can significantly enhance your productivity, a small mistake in a script can also lead to data loss if you’re not careful.

By incorporating these tips into your Excel VBA practice, you can develop more robust, flexible, and efficient scripts.

Each project you undertake offers a unique opportunity to refine your skills and push the boundaries of what you can achieve with Excel and VBA.

Summary

Throughout this post, we’ve explored the dynamic world of Excel VBA, specifically focusing on the powerful capability to insert formulas using VBA.

Starting with a basic example, we demonstrated how to automate the insertion of a SUM formula, easing into more complex scenarios with the SUMPRODUCT formula, and culminating in an advanced application that combined multiple formulas and introduced an array formula.

Each example built upon the last, illustrating the scalability of VBA from simple to complex tasks, empowering users to automate their Excel tasks efficiently.

In summary, mastering how to Insert Formulas Using VBA is an invaluable skill set for anyone looking to enhance their Excel proficiency.

Whether you’re automating routine tasks, conducting intricate data analysis, or aiming to streamline workflows, mastering the insertion of formulas through VBA opens up a world of possibilities.

By embracing the examples provided and applying the additional tips, such as using lastrow to dynamically adjust to data ranges (see my How to find the last row with Excel VBA post for more on that), users can significantly boost their productivity and unlock new levels of data manipulation and analysis in Excel.

Keep Excelling,

As you’ve embarked on the journey of automating Excel with VBA to insert formulas, why stop here? Dive deeper into mastering Excel with another awesome guide: Learn How to Goal Seek in Excel.

Unlock the power to solve for your desired result by adjusting an input value automatically.

It’s a game-changer for financial modeling, budgeting, and beyond. Ready to elevate your Excel skills to new heights? Follow us into the world of Goal Seek and transform the way you analyze data.

With over 20 years in the field, I've become a go-to consultant for all things Excel. From basic formulas to complex macros and dashboards, I've tackled a wide range of Excel challenges. My goal? To demystify Excel's vast capabilities and empower you with practical skills and insights. Join me in this journey to unlock the full potential of Excel, one step at a time. I'm here to share the exploration of Excel's capabilities and help you learn a few things along the way!