如何正确初始化和提取列表框的值 - Userform VBA

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

我有一个用户表单,我想让用户在两个列表框中各选择一个单词,然后将它们保存在一个工作表中。用户也可以(理论上)留下预选的单词。这是我写的代码。

Private Sub UserForm_Activate ()

With ListBox1 'This list is about the stake
.AddItem "Essential"
.AddItem "Important"
.AddItem "Not interesting"
End With
'then I try to initialize the value of the stake. 
ListBox1.Value = "Important"

With ListBox2 'This is a second list, about priority
.AddItem "Auto"
.AddItem "Yes"
.AddItem "No"
End With
'then I try to initialize the value of the priority
Listbox2.Value="Yes"

End sub ()

但我的问题是,尽管两个列表似乎已经被正确初始化(当我运行UserForm时,正确的单词在列表中高亮显示),我无法提取其中一个列表的值。当我运行下面的代码时,.Excel能够提取其中一个列表的值。

Private Sub CommandButton2_Click()
Feuil1.Cells(1,1)=Listbox1.Value
Feuil1.Cells(1,2)=Listbox2.Value
End sub ()

Excel能够提取Listbox2 (Priority) : "Yes "的值,但不能提取Listbox1 (Stake) : "Material "的值。我不明白为什么这段代码对其中一个有效,而对另一个却无效!还有一个因素:如果我手动选择列表框2(优先级):"是",但列表框1(利害关系):"重要 "的值却不行。

还有一个问题:如果我在列表中手动选择一个词,那么Excel能够给我两个列表框的值。

有什么线索吗?

vba listbox userform
1个回答
2
投票

如何获取ListBox的当前值?

看来 .Value 属性可以识别正确的列表行,但不会对第二个列表框做出反应,除非它被聚焦或被手动激活。因此,一个粗暴(不推荐)的解决方法是设置 聚焦 每次你都要获取第二个列表框的当前值,也是如此。这似乎是很麻烦的,在一定程度上类似于永久选择或激活单元格,而不是建议直接引用完全限定的范围。)

'...
Me.ListBox2.SetFocus
Feuil1.Cells(1, 2) = Me.ListBox2.Value

你是肯定的,但是使用列表框的? .List 属性,作为第一个参数表示当前的 "行",以0为基准索引(0等于第1行,1等于第2行等);第二个参数表示当前的 "行"。.ListIndex 作为第一个参数,表示当前的 "行",以0为基数的索引(0等于第1行,1为第2行,等等);第二个参数是 0 表示行的索引(即列的索引 1;btw这里唯一的一个)。)

Private Sub CommandButton2_Click()
Feuil1.Range("A1:B1") = vbNullString
With Me.ListBox1
    If .Listindex >-1 then Feuil1.Cells(1, 1) = .List(.ListIndex, 0)
End With
With Me.ListBox2
    If .Listindex >-1 then Feuil1.Cells(1, 2) = .List(.ListIndex, 0)
End With


0
投票

试试这个,对我很有效。

Private Sub CommandButton2_Click()
Feuil1.Cells(1,1)=Listbox1.Value
Feuil1.Cells(1,2)=Listbox2.Value
Unload Me
End sub 
© www.soinside.com 2019 - 2024. All rights reserved.