VBA example - Microsoft Access: Loop random backcolor


VBA Loop random backcolor

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:

 VBA example - Microsoft Access VBA For Next Random BackColor Form  

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:

VBA example - Microsoft Access VBA For Next Random BackColor Form Design 

- 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

Option Explicit

 

Private Sub Form_Load()

TimerInterval = 300

End Sub

 

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))

Next 

End Sub



Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.