How to add content to the Excel VBA Listbox

Asked

Viewed 668 times

0

Hello, I have a question in a code for Excel VBA. I want the code to search in the spreadsheet the same number that was entered in the TextBox, after finding it sends the information of the entire line of the spreadsheet to the ListBox. How the code is contained in the subroutine AfterUpdate of Textbox, it resets the contents of ListBox rewriting every time on line 0. I don’t know if I was clear. I thank you already.

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

1 answer

1


Problem

You are setting the elements in the listbox from the item with index 0

Dim linhalistbox As Integer
linhalistbox = 0

Solution:

Initializes the variable with the total of elements already present in Listbox

Dim linhalistbox As Integer
linhalistbox = Me.ListBox1.ListCount

Browser other questions tagged

You are not signed in. Login or sign up in order to post.