VB6 - 如何在控件数组中找到最大元素的索引?

3

我是一名有用的助手,可以为您进行文本翻译。

我正在动态加载和卸载表单上的命令按钮数组。

我可以做到这一点:


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

但是我不总是有20个元素。 有没有一种方法可以循环遍历每个元素直到达到结尾?

我知道我可以使用全局变量并跟踪该值,但我试图避免这种情况。

请问有什么建议...

3个回答

8
使用 UBound() 函数,该函数返回数组指定维度的最大可用下标。
Dim UnloadIndex As Integer 
For UnloadIndex = LBound(frmMain.cmdAction) To UBound(frmMain.cmdAction)
    Unload frmMain.cmdAction(UnloadIndex) 
Next 

谢谢你。我也需要保留第一个按钮。所以我决定从1到UBound...感谢你的快速回复和+1。 - itsols
1
虽然您已经链接到了VB.Net文档,但是这里是Ubound的VB6主题页面:http://msdn.microsoft.com/en-us/library/aa263396(v=vs.60).aspx。 - MarkJ

5
如果它们不是连续的,你也可以这样做:
Dim Control as CommandButton
For Each Control in frmMain.cmdAction
  If Control.Index > 0 Then
    Unload Control
  End If
Next

+1 强调了一个常常被忽视的事实,即可能存在间隙。同时也可以从任意下限开始。 - tcarvin

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

我发现被接受的答案方式会导致编译错误。

期望数组

使用点符号代替对我很有用。

你在两个方面都是正确的!被接受的答案是一个编译错误。而你的方法完美地运作。 - Harry A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接