How To Determine Selected Control from Array of Option Buttons

This article was previously published under Q147673
This article has been archived. It is offered "as is" and will no longer be updated.
SUMMARY
This article describes a function you can use to determine which optionbutton in a control array is selected.
MORE INFORMATION
A common programming task in Visual Basic, given a control array of optionbuttons, is to determine which option button in the array is selected. Theoption button that is selected will have its Value property set to True,while all others will have Value properties of False. This article outlinesa short function that will return the index of the selected option buttonwhen it is passed a reference to a control array of option buttons. It willwork correctly even when some indexes are skipped or not present in thecontrol array. In addition, to avoid logic errors in writing code, it willfail and return a -1 if it is passed a control array of another type ofobject (like a check box). The function was contributed by Bruce McKinney,author of Hardcore Visual Basic, which is published by Microsoft Press.

The code for the function is:
Function GetOption(opts As Object) As Integer    On Error GoTo GetOptionFail    Dim opt As OptionButton    For Each opt In opts        If opt.Value Then            GetOption = opt.Index            Exit Function        End If    NextGetOptionFail:    GetOption = -1End Function				
This function can be called like this:
myVariable = GetOption(optMyButtons)   'Control syntax OKmyVariable = GetOption(optMyButtons()) 'Array syntax OK				
KBCONTROL kbVBp400 kbVBp500 kbVBp600 kbVBp kbdsd kbDSupport
Properties

Article ID: 147673 - Last Review: 02/28/2014 08:01:42 - Revision: 2.1

  • Microsoft Visual Basic 5.0 Learning Edition
  • Microsoft Visual Basic 6.0 Learning Edition
  • Microsoft Visual Basic 5.0 Professional Edition
  • Microsoft Visual Basic 6.0 Professional Edition
  • Microsoft Visual Basic 5.0 Enterprise Edition
  • Microsoft Visual Basic 6.0 Enterprise Edition
  • Microsoft Visual Basic 4.0 Standard Edition
  • Microsoft Visual Basic 4.0 Professional Edition
  • Microsoft Visual Basic 4.0 Professional Edition
  • Microsoft Visual Basic 4.0 16-bit Enterprise Edition
  • Microsoft Visual Basic 4.0 32-Bit Enterprise Edition
  • kbnosurvey kbarchive kbhowto KB147673
Feedback