【问题标题】:For Loop through a list boxFor 循环遍历列表框
【发布时间】:2018-01-17 20:22:00
【问题描述】:

希望您能提供帮助 - 我有一个简单的列表框,它是从数据库中填充的,有 6 列 [ID、名称、序号、数据、价格、邮政编码]

列表框的填充没有问题[因此为此我不会发布代码]

我遇到的问题是当我在列表框中选择项目时尝试获取价格的总和。

 With lstOrdersInBatch
   tbxTotal.value = 0
    For IntIndex = 0 To .ListCount - 1
        If .Selected(IntIndex) Then
         'tbxTotal = tbxTotal + .Column(4)
   
           
        End If

    Next
End With

它给了我错误的价值

我已经查看了调试日志,它似乎只选择了最后一个项目而不是全部选择。

希望你能帮忙。

谢谢

请注意是访问VBA编程。

===== 已解决===

Retrieve column values of the selected row of a multicolumn Access listbox

这就是答案。

   With lstOrdersInBatch
   tbxTotal.value = 0
   For IntIndex = 0 To .ListCount - 1
        If .Selected(IntIndex) Then
        tbxTotal = tbxTotal + lstOrdersInBatch.Column(4, IntIndex)
        End If

   Next

结束

感谢您的尝试。

【问题讨论】:

    标签: vba ms-access


    【解决方案1】:

    好的,我已经根据您的评论调整了代码:

    Dim i As Integer
    For i = 0 To Me.lstOrdersInBatch.ListCount - 1
        If Me.lstOrdersInBatch.Selected(i) Then
            tbxTotal = tbxTotal + Me.lstOrdersInBatch.ItemData(i)
        End If
    Next i
    

    【讨论】:

    • 感谢 Winter,但是 - 我犯了一个愚蠢的错误,并没有报告这是访问 VBA 编程 - 因为访问没有获取 ListItem :(
    【解决方案2】:

    您可以使用以下方法减少迭代次数并避免使用 if 语句:

    Dim idx
    tbxTotal = 0
    With lstOrdersInBatch
        For Each idx In .ItemsSelected
            tbxTotal = tbxTotal + .Column(4, idx)
        Next idx
    End With
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2020-12-15
      • 2019-09-07
      • 2015-05-14
      • 2021-04-01
      • 2016-02-05
      相关资源
      最近更新 更多