【问题标题】:Adding rows in a MultiColumn ListBox在多列列表框中添加行
【发布时间】:2015-11-05 01:03:49
【问题描述】:

我在搞乱 VBA,尤其是列表框。

我创建了一个搜索按钮,它使用查找属性 (.Find) 并搜索我们在其数据表的文本框中输入的任何内容。

它可以将搜索结果添加到列表框,但是如果我们想要搜索结果所在的整行,我们如何添加它,而不是像这样vba listbox multicolumn add
如何使用 VBA 完成?
有可能吗?
否则,没有VBA可以吗?

发生了什么:

Data table: a | b | c | d | e
            1 | 2 | 3 | 4 | 5
Search:   a 
Listbox : a

Search:   1 
Listbox : 1

Search:   2
Listbox : 2

Search:   d 
Listbox : d

我“想要”的东西:

Data table: a | b | c | d | e
            1 | 2 | 3 | 4 | 5

Search:  a
Listbox: a | b | c | d | e

Search:  1
Listbox: 1 | 2 | 3 | 4 | 5

Search:  2
Listbox: 1 | 2 | 3 | 4 | 5

Search:  d
Listbox: a | b | c | d | e

如果需要,我可以提供用于测试搜索的代码。

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    可以使用.List 成员访问多列列表框中的项目。该成员接受两个参数作为输入:

    ListBox1.List(RowIndex, ColumnIndex)
    

    RowIndex:我们要访问的记录的行索引。请注意,列表框中的行是从零开始的。因此第一行的索引是0

    ColumnIndex:我们要访问的字段的列索引。请注意,多列列表框中的列也是零索引的。因此,第一列的索引为 0

    例如:

    'Assign values to the columns 
    For i = 1 To 9
        ListBox1.AddItem 'Create a new row
        ListBox1.List(i - 1, 0) = i 'Fill the first column
        ListBox1.List(i - 1, 1) = i * 10 
        ListBox1.List(i - 1, 2) = i * 100 
        ListBox1.List(i - 1, 3) = i * 1000 
    Next i
    

    或者

    但是如果我们想要搜索结果所在的整行,我们如何添加它,而不是像这个 vba listbox multicolumn add 那样做?

    假设您有一个范围对象(例如,rngFound),它代表您的.Find 的结果:

    Me.ListBox1.Clear
    Me.ListBox1.ColumnCount = rngFound.Columns.Count
    Me.ListBox.RowSource = rngFound.Address
    

    【讨论】:

    • 很好的解释。我还对其进行了编辑,以包括使用 RowSource 方法作为替代方法的选项。
    • @DavidZemens :感谢编辑,我忘记了RowSource,因为我已经有几年没用过了!但是OP的完美完成和实际答案! ;)
    • 我忘记了它,因为我主要做 PPT 开发,我对 Excel 做的不多,但我记得 如果您的用户窗体需要使用它会很有用链接到工作表。巧妙的是,ListBox 将反映对工作表的更改,而无需显式“更新”.List 属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多