I couldn’t find a source Microsoft talking about it, but when you define the property RowSource
of a ListBox
, cannot remove or add items in the list.
So what you can do is always popular the list according to what was typed.
Follow an example using the same RowSource
that you provided in the example:
Private Sub FilterBox_Change()
' Carrega a lista com base no texto digitado
ListBox1.List = CarregarLista(ActiveSheet.Range("Customers"), FilterBox.Value)
End Sub
Private Sub UserForm_Initialize()
' Carrega a lista completa
ListBox1.List = CarregarLista(ActiveSheet.Range("Customers"))
End Sub
' Função que retorna um Array com os nomes de um determinado Range nomeado
Private Function CarregarLista(rngNomes As Range, Optional strPesquisa As String) As String()
Dim rangeCount As Long, cont As Long, nomes() As String
cont = 0
' Atua no range informado no parâmetro
With rngNomes
' Define o tamanho do array com base no tamanho do range
ReDim Preserve nomes(.Rows.Count - 1, .Columns.Count - 1)
' Laço que percorre todas as linhas do Range nomeado
For rangeCount = 1 To .Rows.Count
' Caso algum texto seja informado no parâmetro, carrega a lista filtrada
If strPesquisa <> "" Then
' Se o texto informado for parecido com algum nome do range
If UCase(.Cells(rangeCount, 1) & " " & .Cells(rangeCount, 2)) Like "*" & UCase(strPesquisa) & "*" Then
' Adiciona o nome no array
nomes(cont, 0) = .Cells(rangeCount, 1).Value
nomes(cont, 1) = .Cells(rangeCount, 2).Value
cont = cont + 1
End If
Else
' Adiciona o nome no array
nomes(cont, 0) = .Cells(rangeCount, 1).Value
nomes(cont, 1) = .Cells(rangeCount, 2).Value
cont = cont + 1
End If
Next
End With
' Retorno da lista
CarregarLista = nomes
End Function
@Tash_riser to the line
ListBox1.List(i, 0) = NovaLista(i, 0)
worked for you even when the search item is not at the beginning?– Marco
@Marco, this line was really in trouble. It replaces the variable
i
by a variablej
q changes only when theIf
is met.– J. L. Muller