First VBA program

When you create an Excel macro, it automatically defines a new subroutine, which is actually a program that runs after the specified action. You can also create subroutines independently which could be called from other programs, or run in the manner described below. This text will show how a simple code is written and how it is then linked to the objects that are used to launch it.

Open a new Excel document, enter the VBA editor, and then add a new module from the Insert menu. The syntax for creating procedures is as follows:

Sub <procedure name> [(<argument 1>, …, <argument n>]

End Sub

Behind the Sub command, you can specify one or more input arguments in brackets, which can be useful if you invoke subroutine from another program.

Let’s create a procedure called Example and write a simple code:

Sub Example ()

‘My first program

Dim, b, c As Integer

a = 1
b = 2
c = a + b

MsgBox c

End Sub

The first line of code is a comment, which is actually the text cited behind a single quotation mark. Comments are not mandatory, but they are very useful for better documentation of the programs we are writing.

In the program we have further declared the integer variables a, b, and c. The first two were given some value, and the third one was defined as their sum. In the end, we use the MsgBox command, which invokes a method for displaying values ​​within the dialog window, which is the way in which we can display the calculated sum.

Then we need to save the file. Excel will offer us to save it under the XLSM extension as it contains macros.

In order to start the subroutine (same thing as a macro), we need to add an object to which we can join it in the Excel worksheet. The easiest way to do this is by adding a rectangle in which we can type some text, and when we right-click on it, a context menu appears where we select the Assign macro option. Starting the option opens the dialog window in which we select the Example subroutine and link it to the object. The next time we click on the rectangle, this subroutine will start.