VBA and Excel for Engineers and Scientists


Your First VBA Code!

Ok, you’ve stuck with me for this far, the least I can do for you is show you how to implement the classic piece of code that every programmer starts with, “Hello World!”.

In the VBE, go to the “Insert” menu, and choose to insert a “Module”. You will see a code window popup, and if you look in the Project Explorer, you will see that there is a new code module called “Module1”. Type Listing 1 into your code window.

 'Your first VBA Code (this line is a comment) Sub HelloWorld()   MsgBox "Hello World!" End Sub 

Now, you can run it a couple different ways. The first way would be to simply put your cursor somewhere in the code, and press the play button on the menu bar of the VBE. Another way would be to switch back to the main Excel window, and go to click the play button on the Visual Basic toolbar, or from the Tools>Macro menu. Then select to run the “Hello World” subroutine. You should get a window that lists the name of your “Hello World” subroutine and click the “Run” button.

Closure and Next Article

In the next article, we will start to get into more of the VBA language. We will cover various types of containers for your code, variables, data types, functions, etc.