VBA 列表框 - 所选值返回空白

问题描述 投票:0回答:3

我有一个带有一些单选按钮和两个单列列表框的用户窗体。在某些情况下,我无法从第二个列表框返回值。

如果用户选择其中一个单选按钮,他们会在第一个列表框中获得一系列可供选择的项目。一旦他们从第一个列表框中选择,第二个列表框就会填充项目。

如果他们选择其他单选按钮,两个列表框就会填充一个值“不适用”,我会立即选择它。

这是我用来将两个列表框设置为“不适用”的代码

ListBox_First.Clear
ListBox_Second.Clear
ListBox_First.List = Array("Not Applicable")
ListBox_First.Selected(0) = True
ListBox_Second.List = Array("Not Applicable")
ListBox_Second.Selected(0) = True

这是我获取所选值的代码

Dim firstValue As String
Dim secondValue As String
firstValue = ListBox_First.Value
secondValue = ListBox_Second.Value

firstValue
可以,因为它等于“不适用”,但是
secondValue
等于“”。当您查看表单时,每个列表框中的值看起来都已被选中,所以我不明白为什么它是空白的。我已经检查了 ListCount 属性,每个 ListBox 只有一项,因此应该正确选择它。

如果我使用鼠标在第二个列表框中手动选择“不适用”,效果很好,但我试图避免用户在它是唯一值时必须选择它。

我不知道这是否是一个错误,或者我的代码是否做错了什么。

我正在使用一款名为 WRQ Reflections 的产品。

vba listbox userform
3个回答
4
投票

MS 表格的注意事项

Value
财产

除了 Dy.Lees 的有效答案之外,注意最好避免

.Value
并参考例如改为 ListBox2.List(0, 0) 。

进一步注意,由于 MS 帮助参考Value property MS Forms

  • .Value 仅反映“当前选定行的 ►BoundColumn 中的值”,并且
  • 值不能与多选列表框一起使用

3
投票

通过添加setfocus命令来识别该值。

firstValue = ListBox_First.Value
ListBox_Second.SetFocus
secondValue = ListBox_Second.Value

1
投票

如果您不想 SetFocus,这里有一个函数,它将返回列表框中第一个选定的值:

Private Function ListValue(c As Control) As Variant

    Dim i As Long

    For i = 0 To c.ListCount - 1
        If c.Selected(i) Then
            ListValue = c.List(i)
            Exit Function
        End If
    Next

End Function

用途:

firstValue = ListValue(ListBox_First)
secondValue = ListValue(ListBox_Second)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.