Excel 2010 VBA Lesson 5: Writing the Code

[Lesson 4]<<[Table of Contents]>>[Lesson 6]

In order to write the Excel 2010 VBA code, you need to use the Excel 2010 VBA  Editor. The simplest way to launch the Excel 2010 VBA Editor is to insert an Active-X control as shown in Figure 5.1.

vba2010_fig5.1




The most common Active-X control we use is the command button. Proceed to insert the command button. Click on the Active-X command button to enter the Excel 2010 VBA editor. In the editor, you will be presented with the following program structure where you can enter the code in between.

Private Sub CommandButton1_Click()
 Your Code
End Sub

Excel 2010 VBA  code is event driven therefore it will respond to certain events. In the aforementioned example, it will execute when the user clicks on the command button.

Try the following examples:
a)

Private Sub CommandButton1_Click()
 Msgbox "Welcome to Excel VBA 2010"
End Sub

b)

Private Sub CommandButton1_Click()
Dim YourMsg As String
 YourMsg = "Welcome to Excel VBA 2010"
 MsgBox YourMsg
End Sub

c)

Private Sub CommandButton1_Click()
Dim x,y As String
 x=105
 y=20
 MsgBox x mod y
End Sub

c)

Private Sub CommandButton1_Click()
Dim x,y As String
 x=105
 y=20
 MsgBox x mod y
End Sub

* Running the program with return the value of 5

d)

Private Sub
A = "Tom"
B = “likes"
C = “to"
D = "eat"
E = "burger"
MsgBox A + B + C + D + E
End Sub

Running the code produces the sentence  “Tom likes to eat burger”

It produces the same effect if we replace the last line with MsgBox A & B & C & D & E




[Lesson 4]<<[Table of Contents]>>[Lesson 6]