【问题标题】:How to correctly initialize and extract Listbox Value - Userform VBA如何正确初始化和提取列表框值 - Userform VBA
【发布时间】:2020-08-26 09:17:15
【问题描述】:

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

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 ()

但我的问题是,即使这两个列表似乎已正确初始化(运行用户窗体时列表中突出显示的正确单词),我也无法提取其中一个列表的值。当我运行以下代码时:

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

Excel 能够提取 Listbox2(优先级)的值:“是”,但不能提取 Listbox1(股权)的值:“重要”。 我不明白为什么该代码适用于其中一个而不适用于另一个!

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

有什么线索吗?

【问题讨论】:

  • 我无法重现您的问题。命令按钮将单元格 a1 和 b1 的值设置为用户窗体列表框中的选定值
  • 您无法重现该问题并不让我感到惊讶,因为它似乎没有意义。而今天 Excel 无法提取的值发生了变化,现在是无法提取的 listbox2(优先级)。不知道为什么这不起作用并破坏了我的整个(和更复杂的)代码/项目,这非常令人沮丧!感谢您的尝试!

标签: excel vba listbox userform


【解决方案1】:

如何获取 ListBox 的当前值

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

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

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

【讨论】:

  • 谢谢!我尝试了 ListIndex 方法,它有效!非常感谢!
【解决方案2】:

试试这个,它对我很有效。

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

【讨论】:

  • 感谢您的帮助,但我不想卸载用户表单,因为这是之后仍需要运行的更大更复杂代码的一部分。
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 2022-01-01
  • 2010-11-11
  • 2011-12-22
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多