将选定的列表框项目添加到文本框而无需在 VBA Excel 中重置文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23436903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:58:39  来源:igfitidea点击:

Add Selected Listbox Items to Textbox without resetting Textbox in VBA Excel

vbaexcel-vbaexcel

提问by kmw

Currently, I am trying to allow a user to click an item in a list box (listBusFun) and add to a textbox (TextBox2).

目前,我试图允许用户单击列表框 (listBusFun) 中的项目并添加到文本框 (TextBox2)。

I need the textbox NOT to reset as new selections are entered.

我需要文本框不要在输入新选择时重置。

They may select only one item from the listbox, or they may select multiple at a time - but they all need to be added to a textbox.

他们可能只从列表框中选择一项,也可能一次选择多项——但它们都需要添加到文本框中。

If it is easier, I can code this behind a button as well.

如果它更容易,我也可以在按钮后面编码。

I'm not really sure how to do this, but if you could help me out by commenting out the code so I can understand, I would appreciate it.

我不太确定如何做到这一点,但如果您能通过注释掉代码来帮助我理解,我将不胜感激。

Attempted to write this:

试图写这个:

Private Sub btnAddBusinessFunction_Click()  
TextBox2.Text = listBusFun.Text  
End Sub  

回答by David Zemens

Easiest to attach this to a button. You need to iterate the items in the listbox, check to see if each one is selected, and if it is selected, then you append/concatenate it to another string.

最容易将其附加到按钮上。您需要迭代列表框中的项目,检查是否每个项目都被选中,如果被选中,则将其附加/连接到另一个字符串。

I haven't found any VBA specific answers

我还没有找到任何 VBA 特定的答案

Because you're not asking the right question. This is not a problem about listboxes and textboxes or anything, it is simple string concatenation, only slightly complicated by the need to iterate over a list of items and append to the string if the item(s) selected.

因为你没有问正确的问题。这不是关于列表框和文本框或任何东西的问题,它是简单的字符串连接,只是稍微复杂一点,因为需要遍历项目列表并在选择项目时附加到字符串。

Do you understand your own code? Every time you press the button, it's simply overwriting the value in your textbox:

你了解自己的代码吗?每次按下按钮时,它只是覆盖文本框中的值:

Private Sub btnAddBusinessFunction_Click()  
    TextBox2.Text = listBusFun.Text  
End Sub  

Now that I describe the process, does that make a little more sense?

现在我描述了这个过程,这是否更有意义?

Private Sub btnAddBusinessFunction_Click()
    Dim str As String
    Dim i As Long

    'iterate the listbox items and concatente a string
    ' which we will append to the textbox's existing text
    For i = 0 To ListBusFun.ListCount - 1

        If ListBusFun.Selected(i) Then
            If str <> vbNullString Then str = str & ", "
            str = str & ListBusFun.List(i)
        End If

    Next

    'Append this to the existing text in the textbox
    TextBox2.Text = TextBox2.Text & str

End Sub