You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 22 Next »

The tutorials on VBA will include both videos and text. If you have feedback on either, please leave a post on our Forum or send us a mail.

Page content

Hello World

Our first encouter with VBA will be to display the familiar "Hello World" message using a button.

  1. Choose the "Developer" tab and open the VBA editor. If you don't locate the VBA editor, follow this guide. The following window will then open.
  2. To write our first macro, choose "Instert" -> "Module".

  3. First, we will make a Sub procedure that we may later add to our button. All Sub procedures have to begin with Sub and end with End Sub. A Sub can not return a value, and may be compared with a program in other programming languages, where as a function is an alternative. We then call the MsgBox function to create a new window displaying our message.


  4. Lets now return to our Excel sheet to add the button. The insert button feature is shown in the image below.

    Tips: To align the size of the button with existing cells, hold down ALT while resizing. This applies to all sizings!


  5. A new window will open. Choose the "Hello World" macro we just created and click "OK".


  6. We may then rename our button by right-clicking on it and choosing "Edit text".



  7. Finally, we can test our macro by clicking on the button. A window displaying the message "Hello World!" should then open.
    If it does, congratulations! You have just made your first macro using VBA.

Explicit vs implicit variable declaration

Before we look at the different variable declarations, we need to establish the difference between the words explicit and implicit.

  • explicit is defined as: "stated clearly and in detail, leaving no room for confusion or doubt."
  • implicit is defined as: "implied, rather than expressly stated"

When coding in Visual Basic, you are by default not obligated to declare your variables before using them. This an example of an implicit variable declaration.

MyVar = 10

When doing so, VBA will automatically declare it as a variant type provided that the variable has not been declared before. This is a nice feature, but may cause trouble when writing larger scripts. Let's look at an example: We have already written a lot of code using the variable "MyVar". If we were to misspell "MyVar" with "Myvar" in one line, VBA will think of it as a new variable, and declare it automatically, thus not informing us.

MyVar = 4
'We want to multiply MyVar with 10
myvar = MyVar * 10


'... lots of code


'When we finally display MyVar, thinking it equals 40
MsgBox MyVar
'4 is displayed




  • No labels