Log in

View Full Version : Word vba form - textbox to filter listbox items



cjmitton
12-06-2012, 03:29 AM
I have a basic vba form which looks at a folder on my network drive and pulls back a list of the content meeting the relevent criteria.

The user can then select an item and it will be used in some way (generally a document inserted in to a template).

Now the lists are getting very long and the users are complaining slightly. having to scroll up and down to find the one they want. So I want to add a text box in to the form (which I've done called 'FilterTBox') so that when they start to type in the textbox the listbox below (Called 'ListMain') will either filter to show the remaining items or just move to the first item that matches those criteria and highlights it.

i.e. if some type smi it goes to the first record in the list that starts smi

I've seen quite a few options from Excel and not been able to tweak them for Word. I'm sure it can be done but just can't seem to get it!:banghead:

gmaxey
12-06-2012, 05:36 AM
Why don't you use a combo box, match required and match entry.

cjmitton
12-06-2012, 05:49 AM
I thought about that but it would not work with the 'users' we have. There's a combo box already on the form that they can select a sub folder for different contents but sometime they don't know exactly what they want so want to see a list.

Life would be simpler without users, but then again I'd be out of work!

gmaxey
12-06-2012, 09:48 AM
Something like this:

Private Sub TextBox1_Change()
Dim i As Long
Dim lngChars As Long
lngChars = Len(Me.TextBox1.Text)
Debug.Print Me.ListBox1.List(2)
For i = 0 To Me.ListBox1.ListCount - 1
If Left(Me.ListBox1.List(i), lngChars) = Me.TextBox1 Then
Me.ListBox1.ListIndex = i
Exit For
End If
Next i

End Sub
Private Sub UserForm_Initialize()
With Me.ListBox1
.AddItem "Apple"
.AddItem "Bob"
.AddItem "Bill"
.AddItem "Mark"
End With
End Sub

cjmitton
12-06-2012, 09:55 AM
That works!!! Fantastic...

As normal for me theres a but :)

Is there any way of making it not case sensitive? Just tried it on my form and it did not like it that the cases did not match and I thought that I'd messed up the code...

gmaxey
12-06-2012, 10:50 AM
Untested, but try:
If UCase(Left(Me.ListBox1.List(i), lngChars)) = UCase(Me.TextBox1) Then