简体   繁体   English

Excel VBA中ListBox中的持久值

[英]Persistent values in ListBox in Excel VBA

This is my first question in this forum and I am very new to Excel VBA. 这是我在该论坛上的第一个问题,我对Excel VBA还是很陌生。

I have a text box that has an Exit event. 我有一个具有Exit事件的文本框。 My requirement is that when I fill that textbox and exit from there its values should be populated in ListBox. 我的要求是,当我填充该文本框并从那里退出时,其值应填充在ListBox中。 Now, when I am trying to insert the value again inside textbox, it overwrites previous value inside the ListBox. 现在,当我尝试在文本框中再次插入值时,它将覆盖ListBox中的先前值。 I want the values to be persistent. 我希望这些值是持久的。 So the values entered in text box should come in sequence. 因此,在文本框中输入的值应按顺序排列。

Here is what I tried : 这是我尝试的:

ListBox1.ColumnCount = 2 

ListBox1.AddItem 
ListBox1.List(0) = TextBox2.Text 

But then how can I take the next value from Text box and make it visible in List box...(so if I enter 3 values in text box it should show three rows in Listbox) 但是然后我如何才能从文本框中获取下一个值并使其在列表框中可见...(因此,如果我在文本框中输入3个值,它应该在列表框中显示三行)

When you say ListBox1.List(0) = TextBox2.Text , you are telling the code to always add (replace on 2nd instance) to the first item in the listbox. 当您说ListBox1.List(0) = TextBox2.Text ,您是在告诉代码始终将其添加(替换为第二个实例)到列表框中的第一项。

Is this what you are trying? 这是您要尝试的吗?

Private Sub UserForm_Initialize()
    ListBox1.ColumnCount = 2
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    ListBox1.AddItem
    ListBox1.List(ListBox1.ListCount - 1, 0) = TextBox1.Text
End Sub

If you do not need a multi column listbox then the below will also do. 如果不需要多列列表框,则下面的内容也可以。

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    ListBox1.AddItem TextBox1.Text
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM