Excecl VBA Classic Excel VBA 2010 Excel VBA 365 Excel VBA Examples About Us

Dice


A dice is often required as a tool to play board games. It can also be incorporated into VBA games that require a dice. VBA games that you can create in Excel VBA are step and ladder game, monopoly and more.

This example demonstrate how to create an animated dice. When the user click the Spin button, it will start to animate and stop after a certain interval.

To design the interface, insert a UserForm in the VBE. Next, insert a command button and label it as SPIN. Finally, insert seven dot images , as shown in the figure below. Excel VBA will label the images as Image1 to Image7.

The Design Interface

We use the Rnd function to generate random numbers from 1 to 6 using the formula Int(Rnd * 6)+1 that will control the appearance of different combinations of the dots.

Next, we use the Do..Loop procedure and the DoEvents command to animated the dice based on the random numbers. DoEvents is an Excel VBA command that temporarily pauses the execution of the macro to refresh the screen and execute any pending event.

The Code

Private Sub CommandButton1_Click()
x = 0
Do

n = Int(1 + Rnd * 6)

If n = 1 Then
Image4.Visible = True
Image1.Visible = False
Image2.Visible = False
Image3.Visible = False
Image5.Visible = False
Image6.Visible = False
Image7.Visible = False
End If


If n = 2 Then
Image1.Visible = True
Image7.Visible = True
Image2.Visible = False
Image3.Visible = False
Image5.Visible = False
Image6.Visible = False
Image4.Visible = False
End If

If n = 3 Then
Image1.Visible = True
Image4.Visible = True
Image7.Visible = True
Image2.Visible = False
Image3.Visible = False
Image5.Visible = False
Image6.Visible = False
End If
If n = 4 Then
Image1.Visible = True
Image2.Visible = True
Image6.Visible = True
Image7.Visible = True
Image4.Visible = False
Image3.Visible = False
Image5.Visible = False
End If


If n = 5 Then
Image1.Visible = True
Image4.Visible = True
Image2.Visible = True
Image6.Visible = True
Image7.Visible = True
Image3.Visible = False
Image5.Visible = False

End If
If n = 6 Then
Image1.Visible = True
Image2.Visible = True
Image5.Visible = True
Image3.Visible = True
Image6.Visible = True
Image7.Visible = True
Image4.Visible = False
End If

x = x + 2
DoEvents

Loop Until x > 10000

End Sub
 
The Runtime Interface





Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved   [Privacy Policy]

Contact: Facebook Page