Hi,
I have a VBA project. There are two Userforms. On the first Userform, I chose some of them to be enabled and input a value in the respective text box. Then when I press the Next Button, it should control which Labels are enabled and which respective Text boxes have value so it should copy them (Labels and textboxes with its value) to another Userform and arrange them in a Grid (4 column and 3 Rows). The code works with copying but it doesn't work with positioning the labels and textboxes. Anyone can help me to fix this issue?
Here is the code:
I have a VBA project. There are two Userforms. On the first Userform, I chose some of them to be enabled and input a value in the respective text box. Then when I press the Next Button, it should control which Labels are enabled and which respective Text boxes have value so it should copy them (Labels and textboxes with its value) to another Userform and arrange them in a Grid (4 column and 3 Rows). The code works with copying but it doesn't work with positioning the labels and textboxes. Anyone can help me to fix this issue?
Here is the code:
VBA Code:
Private Sub TransferDataToClassForm()
Const MaxPairsPerRow As Integer = 4
Const LabelWidth As Integer = 190
Const TextBoxWidth As Integer = 40
Const ControlHeight As Integer = 22
Const HorizontalSpacing As Integer = 10
Const VerticalSpacing As Integer = 25
Const StartingTop As Integer = 10
Const StartingLeft As Integer = 10
Dim currentTop As Integer: currentTop = StartingTop
Dim currentLeft As Integer: currentLeft = StartingLeft
Dim pairCounter As Integer: pairCounter = 0
Load Class
ClearDynamicControls Class.C_Parameters
Dim ctrl As Control
For Each ctrl In Weight.Controls
If TypeName(ctrl) = "Label" And ctrl.Enabled Then
Dim newLabel As MSForms.Label
Set newLabel = Class.C_Parameters.Controls.Add("Forms.Label.1", "DynamicLabel" & ctrl.Name, True)
newLabel.Caption = ctrl.Caption
newLabel.top = currentTop
newLabel.left = currentLeft
newLabel.width = LabelWidth
newLabel.height = ControlHeight
ElseIf TypeName(ctrl) = "TextBox" Then
Dim tb As MSForms.TextBox
Set tb = ctrl
If tb.Text <> "" Then
Dim newTextBox As MSForms.TextBox
Set newTextBox = Class.C_Parameters.Controls.Add("Forms.TextBox.1", "DynamicTextBox" & ctrl.Name, True)
newTextBox.Text = tb.Text
newTextBox.top = currentTop
newTextBox.left = currentLeft + LabelWidth + HorizontalSpacing
newTextBox.width = TextBoxWidth
newTextBox.height = ControlHeight
pairCounter = pairCounter + 1
If pairCounter >= MaxPairsPerRow Then
currentTop = currentTop + ControlHeight + VerticalSpacing
currentLeft = StartingLeft
pairCounter = 0
Else
currentLeft = currentLeft + LabelWidth + TextBoxWidth + HorizontalSpacing
End If
End If
End If
Next ctrl
Class.Show
End Sub
Private Sub ClearDynamicControls(frm As MSForms.Frame)
Dim i As Integer
For i = frm.Controls.Count To 1 Step -1
Dim ctrl As Control
Set ctrl = frm.Controls(i)
If left(ctrl.Name, 7) = "Dynamic" Then
frm.Controls.Remove (ctrl.Name)
End If
Next i
End Sub