Another Simple is Good example, this time a one-line function that
returns True if the passed control is a member of a control array, or
False if it is not, and without requiring error trapping.
VB's TypeName property returns a string representing the type of control
specified, i.e. pass it a single (non-array) control Text1 and you get "TextBox".
But when TypeName is passed the name of any control that is a member of a
control array VB does not return its specific control type but instead
returns the TypeName "Object". Simple assignment in a wrapper function
creates a Boolean value to differentiate between control arrays and
non-arrayed controls.
Note: the method expects the 'raw' control named passed. For example, if
you have a command button array named Command1(), you would pass the
object Command1 as the parameter to the function to receive the correct
True response. Were you to pass an actual reference to a particular
member of that control array (i.e. Command(3) ), the function correctly
returns False as to that function Command(3) is a specific, identifiable
control (just as non-arrayed controls are).
Place the IsControlInArray() function into a form (or module), declare Public or Private as appropriate, and pass as shown below. |
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
' applications, but you may not reproduce
' or publish this code on any web site,
' online service, or distribute as source
' on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function IsControlInArray(ctl As Object) As Boolean
IsControlInArray = TypeName(ctl) = "Object"
End Function
Private Sub Command1_Click()
Print IsControlInArray(Option1) 'non-array
Print IsControlInArray(Option2) 'array
Print IsControlInArray(Option2(0)) 'array member
Print IsControlInArray(Command1) 'non-array
End Sub |