Learn how to bring your Excel worksheets to life with simple animation techniques
While Excel VBA is primarily used for data processing and automation, it also offers capabilities for creating simple animations and interactive elements. These techniques can be useful for:
This example shows how to make an image move horizontally across the worksheet:
Private Sub StartButton_Click()
repeat:
With VBAProject.Sheet1.Image1
.Left = .Left + 1 ' Move 1 pixel to the right
DoEvents ' Allow other processes to run
If .Left > 200 Then .Left = 1 ' Reset position when reaching edge
End With
GoTo repeat
End Sub
To make an object move vertically, modify the code to use the Top property instead:
Private Sub StartButton_Click()
repeat:
With VBAProject.Sheet1.Image1
.Top = .Top + 1 ' Move 1 pixel down
DoEvents
If .Top > 200 Then ' Check if reached bottom
.Top = 1 ' Reset to top
End If
End With
GoTo repeat
End Sub
Combine both properties for diagonal movement:
Private Sub StartButton_Click()
repeat:
With VBAProject.Sheet1.Image1
.Top = .Top + 5 ' Move down
.Left = .Left + 5 ' Move right
DoEvents
If .Top > 200 Then .Top = 1
If .Left > 200 Then .Left = 1
End With
GoTo repeat
End Sub
Create a more natural bouncing effect with direction changes:
Private Sub StartButton_Click()
Dim xSpeed As Integer, ySpeed As Integer
xSpeed = 2: ySpeed = 2 ' Initial movement speed
Do While True
With VBAProject.Sheet1.Image1
.Left = .Left + xSpeed
.Top = .Top + ySpeed
' Reverse direction when hitting edges
If .Left <= 0 Or .Left >= 300 Then xSpeed = -xSpeed
If .Top <= 0 Or .Top >= 200 Then ySpeed = -ySpeed
End With
DoEvents
Loop
End Sub
Add a stop button for better control:
' Module level variable
Public stopAnimation As Boolean
Private Sub StartButton_Click()
stopAnimation = False
Do While Not stopAnimation
With VBAProject.Sheet1.Image1
.Left = .Left + 1
If .Left > 200 Then .Left = 1
End With
DoEvents
Loop
End Sub
Private Sub StopButton_Click()
stopAnimation = True
End Sub
Copyright ® 2008-2023 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page