Saturday, October 24, 2009

Basics of VBA/What is VBA Post 1.0

Unlike Visual Basic not many people know about Visual Basic for applications(VBA).  Excel has so many features but do you know that you can even add to these features by going behind Excel. To start programming you need a VBA editor. You can arrive at editor by pressing ALT+F11 from key board. Once you press this you will see similar kind of interface as Visual Basic. You will see the VBA project similar to VB. In this project you will have Tool box similar to VB. You can add a Form and can embed different tools such as Text box, radio button etc. You can also insert Module and Class.
VBA is  flexible and you can write various functions, procedures. You can declare variables like integer,double etc like in any other programming language. I will restrict this post to basic and will take up more as we move further.
Let us try to write a simple Hello World program in VBA.
Once you press ALT+F11 you are in VBA editor.
1)Go to 'Insert->Module' on menu bar.
2)Click on the Module1 which is on left side of the page.
3)Go to Tools->Options->Editor->Check the check box 'Require Variable Declaration. To explain why is this required. This is not one of mandatory step, even if you do not check this the code will work fine. This step though provides you an additional feature. If you try to use a variable in a procedure without declaring a variable, code will throw compile error. So you know that you need to declare a variable before using it. In short this helps you to find a defect in code.
4)See program below:


Sub test()
Dim strHelloWorld As String


strHelloWorld = "Hello World"
MsgBox strHelloWorld


End Sub


5)In the above program strHelloWorld  is a string variable which holds the string variable.
Sub stands for procedure. Msgbox will output the string hello world.
6)Compile the code by going to Menu bar Debug->Compile VBA Project. Ensure that code should not throw any error.
7)O/P:Go to Menu Bar Run->Run Sub/UserForm. This pops up form saying Macro. Select the Macro which you want to run. Here you need select sub Test and click on Run.
It displays the output as HelloWorld.


Summary
The above was a simple way to explain about first program in VBA. If anyone has any comment or additional input please go ahead and post comment or initiate discussion.

No comments:

Post a Comment

Followers

About Me

My photo
Hello World!. I am an aspiring blogger, striving towards knowing more about various Technologies and innovating about it. I am full of Energy, Enthusiasm to learn more and more....