How to add content to the Excel VBA ListBox

0

Hello, I have a question in a code for Excel VBA. I want the code to search the worksheet for the same number that was typed in TextBox , after finding it, sends the information from the entire spreadsheet to ListBox . Since the code is contained in the sub routine AfterUpdate of Textbox , it resets the contents of ListBox rewriting every time on line 0. I do not know if I was clear. Thanks in advance.

Private Sub TextBox1_AfterUpdate()

    Dim linhalistbox As Integer
    Dim linha As Integer
    Dim i As Integer
    Dim total As Double

    linhalistbox = 0
    linha = 2
    i = 1
    total = 0

    Do Until Plan2.Cells(linha, 1) = ""
        If TextBox1.Text = Plan2.Cells(linha, 1) Then
            With Me.ListBox1
            .AddItem
            .List(linhalistbox, 0) = i
            .List(linhalistbox, 1) = Plan2.Cells(linha, 3)
            .List(linhalistbox, 2) = Plan2.Cells(linha, 4)
            TextBox2.Text = i
            TextBox5.Text = Plan2.Cells(linha, 4)
            total = total + CDec(TextBox5.Text)
            TextBox6.Text = total
            linhalistbox = linhalistbox + 1
            i = i + 1
            End With
        End If
        linha = linha + 1
    Loop

   TextBox1.Text = ""

End Sub
    
asked by anonymous 15.07.2018 / 03:37

1 answer

2

Problem

You set the elements in the listbox from the item with index 0

Dim linhalistbox As Integer
linhalistbox = 0

Solution:

Initializes the variable with the total elements already present in the ListBox

Dim linhalistbox As Integer
linhalistbox = Me.ListBox1.ListCount
    
15.07.2018 / 11:10