Visual Basic – Understanding Check Boxes

--> (Word) --> (PDF) --> (Epub) --> (Text)
--> (XML) --> (OpenOffice) --> (XPS)
This article has been published [fromdate]

The checkbox acts as a "toggle" control: if it's on, clicking it turns it off; if it's off, clicking it turns it on. Unlike the option button, the operation of each checkbox on a form or frame is independent of all other checkboxes; changing the status of one does not affect other checkboxes.

The program can read or set the status of a checkbox with the Value property (which is the default property of the checkbox).

The Value property of a checkbox is of the Integer type. A value of 0 means "off", a value of 1 means "on". You can use the VB constants vbUnchecked or vbChecked for 0 or 1, respectively.

Following is a checkbox demo. The form contains 6 checkboxes within a frame, named chkHobby1, chkHobby2, until chkHobby6.

The form also contains a command button called cmdOK and a label called lblInfo. This is the form at design time:


The code behind the OK button is:

Private Sub cmdOK_Click()
Dim strInfo As String
strInfo = "Items selected:"
If chkHobby1 = vbChecked Then strInfo = strInfo & " aerobics"
If chkHobby2 = vbChecked Then strInfo = strInfo & " reading"
If chkHobby3 = vbChecked Then strInfo = strInfo & " travel"
If chkHobby4 = vbChecked Then strInfo = strInfo & " movies"
If chkHobby5 = vbChecked Then strInfo = strInfo & " computers"
If chkHobby6 = vbChecked Then strInfo = strInfo & " sports"
lblInfo = strInfo
End Sub

Sample run: