martes, 11 de abril de 2017

Excel Macros Tutorial 1.3 | Sub, Buttons & Message Box

Sub, Buttons & Message Box


In this tutorial we will learn how to create processes with VBA (Visual BASIC for Applications).
The objective is to create a button that displays a message for the user.



To create our program go to the Developer tab and click the Visual Basic button 


You will probably see an empty gray window like this one:


In case you don’t have the Project Explorer or properties window open, go to menu bar and click “View”.
Then activate both windows:



Go to the Project Explorer and click on the “+” next to your file to expand. This will display all your sheets modules and one for the Workbook.

Now go to the second icon from left to right of the top left corner (the one with the rulers) and insert a new module:



A new white page will pop out.

Just for your reference, there are two ways to define routines in visual BASIC. The first one is with “Function” and the other one is with “Sub”. They work almost the same; the only difference is that the function is used to return a value to another function or process, while Subs can be used to update a cell or perform a calculation, but the result can’t be returned to another sub or function.
In this tutorial we will use a Sub routine.

Type down the following:
sub Test1

And click enter.
You will see that excel automatically adds “()” and closes the sub routine with an “End Sub”.
Between these statements we have to write all the code for our process.

The instruction to display a message box is “MsgBox” followed by a space and the message we want to display between double quotes. For example:

MsgBox “Hello World!”

In the end the code will look like this:


Save the file.
** Note :  save the file as a macro-Enabled workbook (*.xlsm)



Now we need to insert a Form Control Button from the Developer tab as shown below:


Click and drag anywhere on the sheet to place the button and a new window will appear



Just select the macro we just created and click the OK button.
Now click the button and you’ll see the message box that pops out with “Hello World!”





No hay comentarios:

Publicar un comentario

Excel Macros Tutorial 1.4 | Types of Variables

to declare a variable, you have to do it like this: dim Variable_Name as Type_of_Variable "Dim" followed by a name for the va...