In this example, you will learn VBA For... Next Loop Statement to generate random back color of labels according to the timer. The example illustrates the RandomBackColor form that has the labels arranged as the word "Hello" like the figure below:
When the form loads and the timer runs, the random color will fill the back color of each label of the word "Hello" (like the figure above) again and again till you close the form or the timer is stopped.
To have the RandomBackColor form as the figure above, you have to create the form in Form Design. See as the figure below:
- Drag and drop label controls as many as you need to arrange them in Hello word.
Then apply the VBA Code below:
Option Compare Database
Private Sub Form_Load()
TimerInterval = 300
Private Sub Form_Timer()
Dim cnt As Control
Dim i As Integer
For i = 0 To Controls.Count - 1
Set cnt = Controls.Item(i)
' Set back style to...
cnt.BackStyle = 1 ' By doing this the back color of labels can be set
Randomize ' Generate the random number seed
' Generate random back color of labels
cnt.BackColor = RGB(CInt(250 * Rnd + 1), CInt(255 * Rnd + 1), CInt(255 * Rnd + 1))
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: