使用 VBA 调整列表框的大小

Resizing a ListBox using VBA

我的用户窗体中有一个列表框,其中填充了 sheet 中的项目。没有多列。此 ListBox 和 UserForm 应根据 ListBox 中的项目数自动调整大小。

当我激活我的用户窗体时,它会调整大小。 ListBox 未正确调整大小。

如果我在调整大小之前放置一个断点,然后使用 F5 或 F8 恢复激活,一切都会按预期进行。我已经这样做了很多次,直到现在都有效。

这是我的用户窗体最初的样子和代码。

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

它应该是这样的:

这是问题发生时的样子:

首先扩大你的用户窗体,然后扩大你的列表框

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

 End If

尝试改写代码。例如,

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

可能 VBA 不希望 ListBox 比当时的表单大。首先尝试设置它的大小。 - 诸如此类。