VBcoders Browse New Submit Contact Sign In

No account? Register free

Forgot password?

Small tips: validate control array index

Vesa Piittinen  (20 Submissions)   VB function enhancement   Beginner   Wed 3rd February 2021

I've seen many ways to check whether a certain control index exists in a control array, where all indexes are not filled. For example, you could have a control array of labels with indexes 0, 1 & 3. I guess one of the most common ways to check for this is to use On Error, but I've always found resorting to rising errors a bad habit to do. A much better another alternative is to loop through the control array using For Each and check for the Index property, but even this becomes a bit silly if you know the index you want to check for and loop the entire control array just to check if it is there or not.


The solution: VarType()


VarType returns the variable type of default property of a control, ie. VarType(MyLabels(1)) returns 8 (vbString), from Caption property. What makes this usable for sniffing for valid index is that VarType returns 9 (vbObject) for invalid indexes! There is no control that returns an object in their default property, making this a perfectly safe method to check if an index exists or not.

Rate Small tips: validate control array index (3(3 Vote))
Small tips: validate control array index.bas

Small tips: validate control array index Comments

No comments yet — be the first to post one!

Post a Comment

0/1000 characters