Milad
Milad

Reputation: 127

VBA - How to resize a VBA UserForm based on its contents

Here is my problem:

I have a simple VBA UserForm and a Label (Label1) inside it which I called it u1_Status to inform users to what is happening behind the processes of my code. Its label will have different text at different stages of my code.

I want my UserForm size change according to the label inside it. For example when I have long informative text in Label1 I want my UserForm size increases and if label1 text in later stages is short my UserForm fits its dimensions to this updates text.

Here is my simplified code so far:

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

The problem is that the width is Ok but the height seems to be Zero.

How my userform should looks:

How my userform should looks

How it Looks with my code:

enter image description here

Upvotes: 0

Views: 1351

Answers (2)

Eduardo
Eduardo

Reputation: 1

Try to use the following code:

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

Upvotes: 0

PeterT
PeterT

Reputation: 8557

The height of the userform also includes the height of the title bar. So you have to use the (read only) InsideHeight property of the userform.

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

Upvotes: 3

Related Questions