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

How to correctly initialize and extract Listbox Value - Userform VBA

我有一个用户表单,我希望用户在其中的两个列表框中分别 select 一个单词,然后将它们保存在 sheet 中。用户也可以(理论上)留下预先 selected 的单词。这是我写的代码:

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 时列表中突出显示正确的单词),我无法提取其中一个的值名单。当我 运行 以下代码时:

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

Excel 能够提取 Listbox2(优先级)的值:“是”,但不能提取 Listbox1(权益)的值:“重要”。 而且我不明白为什么代码对一个有效,对另一个无效!

还有一个元素:如果我手动 select 列表中的一个词,那么 Excel 能够给我两个列表框的值。

有线索吗?

试试这个,对我来说效果很好。

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

如何获取列表框的当前值

似乎 .Value 属性 识别了正确的列表行,但对第二个列表框没有反应,除非它获得焦点或被手动激活。 因此,一个粗暴的(并且不推荐的)解决方法是每次您也必须获取第二个列表框的当前值时设置 focus 。 (顺便说一下,这似乎很伤脑筋,并且在某种程度上类似于永久选择或激活单元格,而不是推荐的直接引用完全限定的范围。

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

您是肯定的,但是使用列表框 .List 属性。 .ListIndex 作为第一个参数表示当前 "row" 通过从零开始的索引(0 等于第 1 行,1 等于第 2 行,等等); 第二个参数 0 表示行索引(即列 1;顺便说一句,这里是唯一的一个)。

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