3

I am dynamically loading and unloading an array of command buttons on a form.

I can do this:

    Dim UnloadIndex As Integer
    For UnloadIndex = 1 To 20
        Unload frmMain.cmdAction(UnloadIndex)
    Next

But I don't always have 20 elements. Is there a way to loop through each one until it reaches the end?

I know I can use a global variable and track the value but I'm trying to avoid this.

Any suggestions please...

itsols
  • 5,406
  • 7
  • 51
  • 95

3 Answers3

8

Use UBound() which returns the highest available subscript for the indicated dimension of an array.

Dim UnloadIndex As Integer 
For UnloadIndex = LBound(frmMain.cmdAction) To UBound(frmMain.cmdAction)
    Unload frmMain.cmdAction(UnloadIndex) 
Next 
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • Thank you for that. I also needed to keep the very first button. So I decided to go from 1 to UBound... Thanks and +1 for your quick response. – itsols Feb 01 '12 at 04:53
  • 1
    +1 although you have linked to the VB.Net docs. Here is the VB6 topic for `Ubound` http://msdn.microsoft.com/en-us/library/aa263396(v=vs.60).aspx – MarkJ Feb 01 '12 at 15:39
5

If they're not sequential, you could also do:

Dim Control as CommandButton
For Each Control in frmMain.cmdAction
  If Control.Index > 0 Then
    Unload Control
  End If
Next
Deanna
  • 23,876
  • 7
  • 71
  • 156
  • +1 for drawing attention to the often over-looked fact that there can be gaps. Also possible to start at an arbitrary lower bound. – tcarvin Feb 01 '12 at 21:27
1
    Dim UnloadIndex As Integer 
For UnloadIndex = LBound(frmMain.cmdAction.LBound) To UBound(frmMain.cmdAction.UBound)
    Unload frmMain.cmdAction(UnloadIndex) 
Next

I found that the accepted answer way gives a compile error

expected array

Using dot notation instead worked for me.

kjack
  • 2,004
  • 3
  • 26
  • 41
  • you are right on both counts! the accepted answer is a compilation error. and your method works perfectly. – Harry A Feb 14 '22 at 19:22