这是我的问题:
我有一个简单的 VBA 用户窗体和一个标签 (Label1) 在里面,我称之为 u1_Status 来通知用户我的代码进程背后发生的事情。它的标签在我的代码的不同阶段会有不同的文本。
我希望根据其中的标签更改我的用户窗体大小。例如,当我在 Label1 中有很长的信息文本时,我希望我的 UserForm 大小增加,如果后期的 label1 文本很短,我的 UserForm 会使其尺寸适合此更新文本。
到目前为止,这是我的简化代码:
sub Test1()
Dim htLabelHeight: htLabelHeight = u1_Status.Label1.Height
Dim wdLabelWidth: wdLabelWidth = u1_Status.Label1.Width
u1_Status.Height = htLabelHeight
u1_Status.Width = wdLabelWidth
u1_Status.Show
end sub
问题是宽度还可以,但高度似乎为零。
我的用户表单应该是什么样子:
我的代码看起来如何:
用户窗体的高度还包括标题栏的高度。所以你必须使用用户窗体的(只读)
InsideHeight
属性。
Option Explicit
Private Sub UserForm_Activate()
With Me
Dim titleBarHeight As Long
titleBarHeight = .Height - .InsideHeight
.Label1.Caption = Sheet1.Range("A10")
.Height = .Label1.Height + titleBarHeight
.Width = .Label1.Width
End With
End Sub
尝试使用以下代码:
Private Sub UserForm_Activate()
' Update Label1 caption based on cell A1
Me.Label1.Caption = Range("A1").Value
' Resize the userform based on the label height
Dim labelHeight As Integer
Dim formHeight As Integer
labelHeight = Label1.Height
formHeight = Me.Height
' Adjust the form height based on the label height and padding
Me.Height = labelHeight + 50 ' Change 50 to adjust for padding as needed
End Sub