Home » excel » excel – Problem with resizing a ListBox programmatically in VBA

excel – Problem with resizing a ListBox programmatically in VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a strange problem and i don’t know what’s going on there. I have a ListBox in my UserForm, which gets filled with items form a sheet. No multi column. This ListBox together with UserForm should resize automatically depending on how many items are in the ListBox.

The problem is, ListBox is not resizing correctly, when i activate my UserForm. UserForm gets resized. However, if i put a breakpoint just before resizing and then resume activation with F5 or F8 all works as intended. That’s why i’m very confuses as to what’s going on there. I have done this many times already and all worked fine till now.

Here is what my UserForm looks like initially and the code.

enter image description here

Private Sub UserForm_Activate()
    Dim i As Long   
    Me.ListBox1.Clear
    For i = 2 To shSet.Range(wConst & "2").CurrentRegion.Rows.Count 
        Me.ListBox1.AddItem shSet.Cells(i, wConst).Value
    Next i
    If Me.ListBox1.Height < Me.ListBox1.ListCount * 14 Then
        Me.ListBox1.Height = Me.ListBox1.ListCount * 14
        Me.Height = Me.ListBox1.Height + 40
    End If
End Sub

Here is what it supposed to look like:

enter image description here

Here is what it looks like, when the problem occurs:

enter image description here

Anybody knows what’s causing this problem? Thx in advance.

How to&Answers:

First make your Userform larger, then after that your Listbox

If Me.ListBox1.Height < Me.ListBox1.ListCount * 14 Then
    Me.Height = Me.ListBox1.Height * 14 + 40
    Me.ListBox1.Height = Me.Height - 40

 End If

Answer:

Try rephrasing the code. For example,

Dim Hight As Single

Hight = (i - 2) * 14 + 40
If Me.Height <> Hight Then
    With Mw.ListBox1
        If .Height <> (Hight - 40) Then .Height = Hight - 40
    End With
    .Height = Hight
End If

Perhaps VBA doesn’t like the ListBox to be bigger than the form at that moment. Try setting its size first. – That sort of thing.