Search

VBA to automatically add Controls in Design Mode to UserForm on Run-Time

As I mentioned in tutorial https://youtu.be/csUhqCN0CBI this code is rough but works.

find below VBA code to automatically add Controls like Labels, Textbox etc to UserForm on Run-Time.

Download Project here: https://bit.ly/3aKfrFS

Or copy the code from below:


Option Explicit

Sub addCtrls()
'-----------------------------
'Thanks for downloading the code.
'Please visit our channel for a quick explainer on this code.
'Feel free to update the code as per your need and also share with your friends.
'Download free codes from http://vbaa2z.blogspot.com
'Subscribe channel: youtube.com/vbaa2z
'Author: L Pamai (vbaa2z.team@gmail.com)
'-----------------------------

't1-54;114;108;78
'T54, 60/42, T54
Dim UFvbc As VBComponent
Dim r As Long

Set UFvbc = ThisWorkbook.VBProject.VBComponents("UserForm1")
Dim cb As Control
Dim t As Long, h&, w&, rowCnt&, ColCnt&, objLeft&, vGap&, objLeft_last&, totalColumns&
Dim objRow_last As Long
Dim TotalRows&

t = 15 'top
h = 10 'hieght
w = 84 'width

rowCnt = 1
ColCnt = 1
objLeft = 40
objLeft_last = 10

vGap = 14
objRow_last = 20

TotalRows = 12
totalColumns = 4

For r = 1 To (TotalRows * totalColumns) '(6 * 7)

Set cb = UFvbc.Designer.Controls.Add("Forms.Label.1", "Label" & r, True)
'Set cb = UFvbc.Designer.Controls.Add("Forms.Textbox.1", "Textbox" & r, True)
    
    't1_r1_c1
    cb.Name = "t1_r" & rowCnt & "_c" & ColCnt
    cb.BackColor = &HC0C0C0   'vbGreen
    cb.Height = h
    cb.Width = w
    cb.Top = objRow_last

    '----------------------
    If ColCnt = 1 Then
      cb.Left = objLeft
      objLeft_last = objLeft
      'vGap = 1
    Else
      cb.Left = objLeft_last + w + vGap
      objLeft_last = objLeft_last + w + vGap
    End If
    
    ColCnt = ColCnt + 1
    '----------------------
    
    If ColCnt = totalColumns + 1 Then
      ColCnt = 1
      rowCnt = rowCnt + 1
      objLeft_last = 10
      objRow_last = objRow_last + h + vGap
        
    End If
    
  Set cb = Nothing
  
Next r

End Sub

No comments:

Post a Comment

Note: only a member of this blog may post a comment.