Formulário com uma Listbox e um Textbox de pesquisa

653mrj

18-05-2011 16:18:42

Boa tarde,

Eu estou com algumas dificuldades para criar uma pesquisa num formulário com um TextBox, e com um ListBox, num livro de Excel.
O que eu pretendo é que ao digitar no TextBox, a Listbox seja filtrada, aparecendo só o valor que eu pretendo, até aqui eu já consegui fazer o código VBA e funciona bem, o que eu também queria é que a Listbox tivesse o cabeçalho da primeira linha da folha de excel e que esse cabeçalho não desaparecesse com a pesquisa.

Resumidamente é assim:
- O livro só tem uma folha (é uma folha de contactos telefónicos);
- Nessa folha na primeira linha é o cabeçalho com 8 colunas, que eu pretendo que apareça também na Listbox;
- O número de linhas de momento são 115, mas poderão chegar às 200/250;
- No formulário de pesquisa quero que tenha um Textbox e uma Listbox em que apareça o cabeçalho;
- No Textbox, quando eu digito algum texto quero que o Listbox vá filtrando a informação, até aparecer a informação correcta, sem perder o cabeçalho;

Gostaria que alguém me pudesse ajudar, pois eu já andei a pesquisar na net e não encontrei o que pretendo.


Aqui vai o código que eu tenho e que funciona com a pesquisa (não aparece o cabeçalho):

Option Explicit
Private TextoDigitado As String

Private Sub Textbox1_Change()
TextoDigitado = TextBox1.Text
Call preenchelista
End Sub

Private Sub UserForm_Initialize()
Call preenchelista
End Sub

Private Sub preenchelista()
Dim ws As Worksheet
Dim i As Integer
Dim TextoCelula As String
Set ws = ThisWorkbook.Worksheets("LISTA")
i = 2

Me.ListBox1.Clear
Me.ListBox1.ColumnHeads = True
Me.ListBox1.ColumnCount = 8
Me.ListBox1.ColumnWidths = "30;150;70;70;70;70;70;70"

With ws
While .Cells(i, 2).Value <> Empty
TextoCelula = .Cells(i, 2).Value
If UCase(Left(TextoCelula, Len(TextoDigitado))) = UCase(TextoDigitado) Then
Me.ListBox1.AddItem ws.Range("A" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 1) = ws.Range("B" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 2) = ws.Range("C" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 3) = ws.Range("D" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 4) = ws.Range("E" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 5) = ws.Range("F" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 6) = ws.Range("G" & i)
Me.ListBox1.List(Me.ListBox1.ListCount - 1, 7) = ws.Range("H" & i)

End If
i = i + 1
Wend
End With
End Sub

Mauro Coutinho

24-05-2011 00:47:03

Para se Trabalhar com Cabeçalho em ListBox, tem de usar a Propriedade RowSource, e para isso o Filtro primeiro tem de ir para uma aba e depois devolve-lo para o ListBox.
No Modelo Cadastro desenvolvido pelo Tomas tem um Form de Pesquisa que filtra em um ListBox conforme o que foi digitado no TextBox, com uma rotina propria para criar o Cabeçalho, baixe o Modelo e de uma olhada se ajuda.
Agora dependendo do seu Modelo, o melhor seria trocar o ListBox por ListView, pelo fato deste aceitar varios tipos de configuração,
No Tópico DICAS tem alguns exemplos de ListBox e Listview, vale a pena baixar e estuda-los.
DICAS
viewforum.php?f=17

abraços

joseA

24-05-2011 15:10:46

Veja um exemplo aplicando o controle ListView.

653mrj

25-05-2011 16:57:57

Muito obrigado pela ajuda aos dois, eu gosto mais do ListView, dá um ar mais profissional :)
Só tenho é uma dúvida, o código abaixo funciona na perfeição, como é que eu faço depois de uma pesquisa ao limpar o conteúdo do textbox, a ListView carregue novamente a informação.
Isto é, ao pesquisar aparece o valor que pretendo depois eu tenho por habito limpar o textbox, eu queria que ao fazer isto que os dados carregados no formulário no início voltassem aparecer. Com este código não aparecem fica o ListView em branco :(.
Se me puderem ajudar eu desde já agradeço.


Private Sub Userform_Initialize()
Call preenchelistview
End Sub

Private Sub TextBox1_Change()
Dim strObjetoBuscar As String
Dim lngResultado, lastRow As Long
'Dim lngColumna As Long, lngFila As Long
Dim a As Integer
Dim coluna
coluna = 2
ListView1.ListItems.Clear
strObjetoBuscar = TextBox1.Value
If strObjetoBuscar = vbNullString Then GoTo 99
strObjetoBuscar = LCase(strObjetoBuscar)
lastRow = Folha1.Cells(Folha1.Cells.Rows.Count, "a").End(xlUp).Row

For a = 2 To lastRow
lngResultado = InStr(1, Folha1.Cells(a, coluna), strObjetoBuscar, vbTextCompare)
If lngResultado > 0 Then
Set li = ListView1.ListItems.Add(Text:=Format(Folha1.Range("a" & a).Value, "0"))
li.ListSubItems.Add Text:=Folha1.Range("b" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("c" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("d" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("e" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("f" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("g" & a).Value
End If
Next a
99:
End Sub

Private Sub preenchelistview()

Dim lin As Integer

' Adiciona as colunas
With ListView1
.Gridlines = True
.View = lvwReport
.FullRowSelect = True
.ColumnHeaders.Add Text:="ID", Width:=20
.ColumnHeaders.Add Text:="Nome", Width:=111
.ColumnHeaders.Add Text:="Morada", Width:=111
.ColumnHeaders.Add Text:="Cód. Postal", Width:=111
.ColumnHeaders.Add Text:="NIF", Width:=45, Alignment:=2
.ColumnHeaders.Add Text:="Telefone", Width:=48, Alignment:=2
.ColumnHeaders.Add Text:="Fax", Width:=50, Alignment:=2
.ColumnHeaders.Add Text:="E-Mail", Width:=111
End With

' Adiciona itens a lista
lin = 2
Do Until Sheets("lista").Cells(lin, ID) = ""
Set li = ListView1.ListItems.Add(Text:=Sheets("lista").Cells(lin, ID).Value)
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, NOME).Value
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, MORADA).Value
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, POSTAL).Value
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, NIF).Value
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, TEL).Value
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, FAX).Value
li.ListSubItems.Add Text:=Sheets("lista").Cells(lin, EMAIL).Value
lin = lin + 1
Loop
End Sub

joseA

25-05-2011 22:08:22

Tente assim,

No ambienet VBA do form dê um duplo click no TextBox1, apague todo evento associado à ele e copie/cole, substtuindo pelas linhas abaixo:

Código: Selecionar todos

Private Sub TextBox1_Change()
If Me.TextBox1 = "" Then
    Call PreencherListView
    Me.Label2.Caption = Format(ListView1.ListItems.Count, "00")
Else

Dim strObjetoBuscar As String
Dim lngResultado, lastRow As Long
'Dim lngColumna As Long, lngFila As Long
Dim a As Integer
Dim coluna
coluna = 2
ListView1.ListItems.Clear
strObjetoBuscar = TextBox1.Value
If strObjetoBuscar = vbNullString Then GoTo 99
strObjetoBuscar = LCase(strObjetoBuscar)
lastRow = Folha1.Cells(Folha1.Cells.Rows.Count, "a").End(xlUp).Row

For a = 2 To lastRow
lngResultado = InStr(1, Folha1.Cells(a, coluna), strObjetoBuscar, vbTextCompare)
If lngResultado > 0 Then
Set li = ListView1.ListItems.Add(Text:=Format(Folha1.Range("a" & a).Value, "0"))
li.ListSubItems.Add Text:=Folha1.Range("b" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("c" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("d" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("e" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("f" & a).Value
li.ListSubItems.Add Text:=Folha1.Range("g" & a).Value
End If
Next a
99:
Me.Label2.Caption = Format(ListView1.ListItems.Count, "00")
End If
End Sub

653mrj

26-05-2011 08:29:39

Muito Obrigado funciona muito bem, é isto que eu pretendia.

joseA

26-05-2011 13:26:46

Estando ao nosso alcance disponha.