Excel Guides

Understanding Subroutines in Excel

A subroutine is a set of instructions that performs a specific task. In Excel, subroutines are written in Visual Basic for Applications (VBA), and they can be used to automate tasks in a workbook. You can write your own subroutines, or you can use pre-written subroutines called macros. Macros are written in VBA and are stored in macro-enabled workbooks (.xlsm files).

When you create a subroutine, you give it a name and specify the task that it will perform. For example, you might create a subroutine that calculates the average of a range of cells. Once you have created the subroutine, you can run it by clicking a button or by using a keyboard shortcut. You can also run the subroutine from another subroutine or from a worksheet function.

Subroutines can take arguments. An argument is a value that is passed to the subroutine when it is run. For example, if you have a subroutine that calculates the average of a range of cells, you would need to specify the range of cells as an argument when you run the subroutine. Arguments are optional; you do not need to specify an argument if the subroutine does not require one.

You can return values from a subroutine. A return value is a value that is passed back to the code that called the subroutine. For example, if you have a subroutine that calculates the average of a range of cells, you could return the average as the return value. Return values are optional; you do not need to specify a return value if the subroutine does not have one.

Creating Subroutines

You can create your ownsubroutines, or you can use pre-written macros. Macros are written in VBA and are stored in macro-enabled workbooks (.xlsm files).

Creating Your Own Subroutines

To create your ownsubroutines:

  1. Open the Visual Basic Editor (VBE) by pressing Alt+F11 on your keyboard.
  2. In the Project Explorer pane, double-click ThisWorkbook to open it in the Code window.





  3. Move beyond 

    Excel

    Get started with Causal today.
    Build models effortlessly, connect them directly to your data, and share them with interactive dashboards and beautiful visuals.