将文本框搜索到列表框多列

时间:2015-08-15 02:07:17

标签: excel-vba vba excel

我有一个完美的代码工作,搜索工作表中的项目,然后在列表框中显示userform文本框。但不知何故,它只显示在列表框中的一列中。 我想在lisbox中显示4列。

代码:

Private Sub TextBox1_Change()

     Dim search As Variant 
     Dim textbox As Variant 
     Dim index As Variant 
     Dim item As Variant 
     Dim result As Variant 
     Dim match As Integer

     With Me.ListBox1 
     .RowSource = "" 
     End With

     On Error GoTo skip match = 0 ListBox1.Clear

     With Range("Forcast")

         Set textbox = .Find(TextBox1, LookIn:=xlValues, lookat:=xlPart)
         If Not textbox Is Nothing Then
             index = textbox.Address
             Do
                 result = Sheets("Report").Cells(Range(textbox.Address).Row, 1).Value
                 For Each item In ListBox1.List
                     If item = result Then match = 1
                 Next item
                 If match = 0 Then ListBox1.AddItem result
                 listbox1.ColumnCount = 4
                 Set textbox = .FindNext(textbox)
                 match = 0
             Loop While Not textbox Is Nothing And textbox.Address <> index
         End If End With

    End Sub

1 个答案:

答案 0 :(得分:0)

将项目添加到ListBox的两种方法:

Option Explicit

Private Sub UserForm_Initialize()

    With ListBox1


       .ColumnCount = 4 '---------------------------------------------

        'add a 2 dimensional array
        .List = Worksheets(1).Range("A1:D3").Value2 '3 rows, 4 columns

        'add a 2 dimensional array
        .List = Worksheets(1).Range("A1:D1").Value2 '1 rows, 4 columns



       .ColumnCount = 1 '---------------------------------------------

        'add a 1 dimensional array
        .List = Array(1, 2, 3, 4)                   '4 rows, 1 column

        'same as above:                             '4 rows, 1 column
        .AddItem "1"
        .AddItem "2"
        .AddItem "3"
        .AddItem "4"

    End With

End Sub