I have a userform with a textbox and a listbox with the following plan:
- Users input text in
Textbox1
. - Every time
Textbox1.Text
changes, a search with the following features is performed:Textbox1.Text
is searched in a specific range in a worksheet.Textbox1.Text
can be found more than once.Listbox1
is populated with the results of the search.
So far so good. Due to having large set of data, the list can get many items. In this case the list reaches out of the screen and I had to limit Listbox1.Height
. This is the code for the above:
Private Sub TextBox1_Change()
Dim srchWord As String, firstAddress As String
Dim srchRng As Range, cell As Range
Dim maxRow As Integer
ListBox1.Clear
If TextBox1.Value = "" Then
ListBox1.Height = 0
Else
With ThisWorkbook.Worksheets(1)
maxRow = .Cells(.Rows.Count, 2).End(xlUp).Row
Set srchRng = .Range("A2:A" & maxRow)
End With
srchWord = TextBox1.Value
Set cell = srchRng.Find(srchWord, LookIn:=xlValues, lookat:=xlPart)
With ListBox1
If Not cell Is Nothing Then
firstAddress = cell.Address
Do
If Not cell.Value Like "*(*" Then
.AddItem (cell.Value)
Select Case .ListCount
Case Is < 2
.Height = 17
Case Is < 21
.Height = 15 * .ListCount
Case Else
.Height = 272.5
End Select
Me.Height = 500
End If
Set cell = srchRng.FindNext(cell)
Loop While Not cell.Address = firstAddress
End If
End With
End If
End Sub
The problem was in Case Else
when scroll was enabled I couldn't reach the last item of the list. By searching on the net I found some potential solutions:
- set
Listbox1.IntegralHeight = False
set the height and then set againListbox1.IntegralHeight = True
- set
Listbox1.MultiSelect = fmMultiSelectSingle
and then set againListbox1.MultiSelect = fmMultiSelectExtended
. - do both of the above.
Application.Wait (Now + TimeValue("0:00:01") * 0.5)
and then set the height.
None of these worked. To be able to scroll to the last item, this worked:
Listbox1.IntegralHeight = False
Listbox1.Height= x
Listbox1.IntegralHeight = False
Listbox1.Height= x
but this also set the Listbox1.Height to this of one single item. (with arrows at the right)
Does anybody know how on earth am I going to control the Listbox1.Height without all this unwanted behaviour? Also if somebody can suggest another structure that could follow the plan mentioned at first, I 'm willing to discard the listbox.