Home > Enterprise >  VBA - How to resize a VBA UserForm based on it's contents
VBA - How to resize a VBA UserForm based on it's contents

Time:12-11

I know that this must be duplicate question but I couldn't find my problem along other similar questions.

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. It's 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 is's 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

CodePudding user response:

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
  • Related