【问题标题】:Resizing a ListBox using VBA使用 VBA 调整列表框的大小
【发布时间】:2020-07-01 05:02:29
【问题描述】:

我的用户窗体中有一个列表框,其中填充了工作表中的项目。没有多列。这个 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

它应该是这样的:

出现问题时的外观如下:

【问题讨论】:

  • 显示你用来实例化用户表单的对象
  • 现在我只是按 F5 来运行该用户窗体。
  • 尝试从标准模块中的 sub 启动它

标签: excel vba listbox


【解决方案1】:

先让你的用户表单变大,然后再让你的列表框变大

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

 End If

【讨论】:

  • 是的,第一次调整用户窗体的大小,然后 ListBox 解决了这个问题。
  • 好吧,按照最初的逻辑,它应该首先是Me.Height = Me.ListBox1.ListCount * 14 + 40,然后是Me.ListBox1.Height = Me.Height - 40
  • 是的,我就是这样做的。
  • 谢谢HTH,我没有看第二行,编辑了它
【解决方案2】:

尝试改写代码。例如,

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 在那个时候比表单大。尝试先设置它的大小。 - 那种东西。

【讨论】:

  • 是的,VBA 不喜欢这样。我交换了调整大小的顺序,现在一切都很好。
猜你喜欢
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多