Program Example 15 Control Arrays 1: Objectives
Program Example 15 Control Arrays 1: Objectives
Program Example 15 Control Arrays 1: Objectives
Objectives
• Display single colours in a grid of shapes • Make and use a Control Array
• Display patterns of colours in a grid of shapes • Use a fixed loop (FOR..NEXT) to manipulate properties
of a control array
• Use the eight built-in Visual Basic Colour Constants
• Use simple Message Boxes and Message Box Constants
• Use the multiple branching structure:
SELECT..CASE..END SELECT
Design Notes
This project is a simple introduction to the use of control arrays. A control array is a collection of objects of the
same type, which have the same name but different index values. Using loops and variables, it very easy
to manipulate the properties of a control array. Each element of the array is referenced by its unique ‘index
value’.
In this example, we use the colour property of the shapes to demonstrate the ease of use of the control array.
Visual Basic 6.0 has eight built-in colour constants: vbBlack, vbBlue, vbWhite, vbYellow, vbGreen, vbRed,
vbCyan and vbMagenta. Note: Microsoft always use the American spelling of the word ‘colour’, i.e. ‘color’.
When creating the squares, set the Font, BackStyle and BackColor for the first one, then copy and paste it.
When copying and pasting, the application will ask the question: “Do you want to create a control array?” In
this case, answer “Yes”.
The captions on the command buttons give clues as to the names of the objects. Always set the name
properties before entering any code.
Interface
Code
GENERAL SECTION
Const NumButtons = 9
Const MsgColour = "The colour has been changed to "
Const MsgQuestion = "Do you really want to change the colour to "
EVENTS
For i = 0 To NumButtons - 1
shpCell(i).BackColor = vbBlack
Next i
Else
For i = 0 To NumButtons - 1
shpCell(i).BackColor = vbBlue
Next i
End If
End Sub
For i = 0 To NumButtons - 1
shpCell(i).BackColor = vbBlue
Next i
End Sub
End If
Private Sub cmdWhite_Click()
Next i
'set all to white
End Sub
For i = 0 To NumButtons - 1
Select Case i
Case 2, 4, 6
shpCell(i).BackColor = vbMagenta
Case Else
shpCell(i).BackColor = vbYellow
End Select
Next i
End Sub
2. Which two lines of code decide whether or not to set the colour of all the shapes to black?
3. The built-in Visual Basic constants ‘vbYesNoCancel’ and ‘vbQuestion’ determine the appearance of the MsgBox
Form. Name three other possible combinations of constants that could be used.
Hint: Start typing Msgbox “Prompt” in your project and the options will appear in a dropdown box.
4. What is the essential difference between the following two lines of code?
Const Numbutton = 9
Why then do we then loop from 0 to 8 in the program when manipulating the shape colour properties? i.e.
For i = 0 to NumButtons - 1 ….
7. Extend the grid to 16 buttons. Modify the code to ensure that all the command buttons function correctly.