Results 1 to 1 of 1

Thread: Classic VB - How do I detect if an index exists in a control array?

  1. #1

    Thread Starter
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Classic VB - How do I detect if an index exists in a control array?

    By using the VarType function provided by VB we get rather odd results: it returns the default property's data type for controls that exist and are initialized while the unused indexes give the more expected result of vbObject. Since none of the controls default property returns an object we can safely use this as our detection.

    Thus to check whether a control index already exists, start a new project and add a new command button, name it cmdArray and set it's Index to 0 in the property window, then paste:
    Code:
    Private Sub Form_Load()
        Dim intA As Integer
        
        Load cmdArray(5)
        Load cmdArray(3)
        Load cmdArray(1)
        Load cmdArray(2)
        
        For intA = cmdArray.LBound To cmdArray.UBound
            If VarType(cmdArray(intA)) <> vbObject Then
                Debug.Print "Index " & intA & " exists!"
            Else
                Debug.Print "Index " & intA & " IS MISSING!"
            End If
        Next
    End Sub
    You get:
    Index 0 exists!
    Index 1 exists!
    Index 2 exists!
    Index 3 exists!
    Index 4 IS MISSING!
    Index 5 exists!



    If you wish to have an easy-to-use function, then this will do:
    Code:
    Public Function HasIndex(ControlArray As Object, ByVal Index As Integer) As Boolean
        HasIndex = (VarType(ControlArray(Index)) <> vbObject)
    End Function
    Last edited by Merri; Jun 6th, 2009 at 02:02 PM. Reason: Updated slightly thanks to LaVolpe

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width