Excel VBA 2010 Lesson 25: Creating Animation in Excel VBA 2010

TwitterShare/Bookmark

 [Lesson 24][Table of Contents] [Lesson 26]

Beside creating Excel VBA  2010 code for mathematical and financial calculations, it is also possible to creating some fun applications in Excel VBA 2010, including games and animation. Although professionals programmers might not be interested to write such applications, it is worth while trying them out as a hobby and for personal satisfaction.

Animation can be achieved by changing the position of an object continuously using a looping sub procedure. Two properties or functions that are required to change the positions or coordinates of the object are the Left and Top properties. The Left property specifies the distance of the left edge of the object in pixel from the left border of the screen and the Top property specifies the distance of the top edge of the object from the top border of the screen.

For for example, the following code makes the object move from left to right then back to left again repeatedly until the user press the stop button. The reset button move the object back to the starting position. You need to insert the image control into the spreadsheet in order for this code to work.


The code:

Private Sub CmsStart_Click()
repeat:With VBAProject.Sheet1.Image1
.Left = .Left + 1
DoEvents
If .Left > 200 Then .Left = 1
End WithGoTo repeat

End Sub

The code for the reset button is

Private Sub CmdReset_Click()
With VBAProject.Sheet1.Image1
.Left = 0
End With
End Sub

*The above code reset the position of the image to the far left

vba2010_figure25.1

           Figure 25.1

If you wish to move the object up and down, change the above code by replacing the property Left to Top, the code is as follows:

Private Sub StartButton_Click()
repeat:With VBAProject.Sheet1.Image1
.Top= .Top+ 1
DoEvents
If .Top> 200 Then .Top = 1
End WithGoTo repeat

End Sub


If you wish to make the object move diagonally, then use the properties Top and Left at the same time, as follows:
Private Sub StartButton_Click()
repeat:

With VBAProject.Sheet1.Image1

.Top = .Top + 5
.Left = .Left + 5

DoEvents
If .Top > 200 Then .Top = 1
If .Left > 200 Then .Left = 1

End With

GoTo repeat
End Sub

  [Lesson 24][Table of Contents]  [Lesson 26]