为什么不能在 VBA 中像这样来自列表框的 select 变量?

Why cant select variables from listbox like this in VBA?

大家好,我想 select 一些变量从 "Variable(s)" 列表框到 "Row" and/or "Column" 列表框。

我知道我应该这样写:

   For irow = lbxVar.ListCount To 1 Step -1
        If lbxVar.Selected(irow - 1) = True Then
        lbxColumn.AddItem lbxVar.List(irow - 1)
        lbxVar.RemoveItem (irow - 1)
  End If
Next irow

I just don't understand why I cannot write the code like this?

If lbxVar.ListIndex > -1 Then
    For irow = 0 To lbxVar.ListCount - 1
        If lbxVar.Selected(irow) = True Then
        lbxColumn.AddItem lbxVar.List(irow)
        lbxVar.RemoveItem (irow)
    End If
Next irow
End If

显示错误:

谢谢。

您必须向后循环集合的原因是,当您从列表中删除一个项目时,lbxVar.ListCount 会变小。

然而,在 For 循环中,迭代次数在开始执行后是固定的 - 表达式 lbxVar.ListCount - 1 仅计算一次。发生的情况是,如果删除任何项目,就会超出 lbxVar.Selected.

的范围

当你向后循环时,你不会遇到这个问题,因为它只会改变你已经迭代过的项目的索引。如果将它们添加到第二个列表框的顺序是您试图通过向前而不是向后遍历索引来保留的顺序,则您必须循环遍历所选项目两次 - 一次复制到另一个列表框,一次删除它们:

If lbxVar.ListIndex > -1 Then
    'Add pass:
    For irow = 0 To lbxVar.ListCount - 1
        If lbxVar.Selected(irow) Then
            lbxColumn.AddItem lbxVar.List(irow)
        End If
    Next irow
    'Remove pass:
    For irow = lbxVar.ListCount To 1 Step -1
        If lbxVar.Selected(irow - 1) Then
            lbxVar.RemoveItem (irow - 1)
        End If
    Next irow
End If