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



我有一个用户窗体,我希望用户在两个列表框中选择一个单词,然后将它们保存在工作表中。用户还可以(理论上(离开预先选择的单词。这是我编写的代码:

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 (Priority( : "Yes" 的值,但不能提取 Listbox1 (Stake( : "Important" 的值。而且我不明白为什么代码适用于一个而不适用于另一个!

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

有什么线索吗?

如何获取列表框的当前值

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

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

但是,使用列表框的.List属性,您是确定的。.ListIndexas 第一个参数通过从零开始的索引表示当前"行"(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

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

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

最新更新