I want to create dynamic buttons and then implement the click method, but any help on the internet does not work here. I hope someone can help me here.
It is not possible to create all buttons. Unfortunately, there is no possibility to write in other languages because we can only use Excel and may.
This is about the infoBtn1_Click.
My Script
Option Explicit
Dim WithEvents infoBtn As MSForms.CommandButton
Dim WithEvents infoBtn1 As MSForms.CommandButton
Dim WithEvents frameCard As MSForms.frame
Dim WithEvents cardTitel As MSForms.Label
Dim WithEvents ausLabel As MSForms.Label
Dim WithEvents ausbilderLabel As MSForms.Label
Dim WithEvents amLabel As MSForms.Label
Dim WithEvents datumLabel As MSForms.Label
Dim WithEvents infoLabel As MSForms.Label
Dim add As Integer
Dim topPos As Integer
Dim ctl As Control
Dim n As Integer
Dim VorhabenArray() As Variant
Dim Free(1 To 5) As Long
Dim sh As Worksheet
Dim v As Range
Dim arr(0 To 40) As Integer
Dim i As Integer
Dim ausbildungNr As String
Dim speicher As String
Private Sub CommandButton1_Click()
If ComboBox1.Value = "" Then
MsgBox "Bitte tragen Sie eine Ausbildung ein."
Exit Sub
End If
ausbildungSuche.ausbildungCB.Value = ComboBox1.Value
Unload Me
Call ausbildungSuche.suchenBtn_Click
End Sub
Private Sub infoBtn1_Click()
MsgBox "test"
End Sub
Private Sub UserForm_Activate()
On Error GoTo fehler
ComboBox1.List = Sheets("Meta").Range("A1:A8").Value
speicher = ausbildungSuche.ausbildungCB.Value
Select Case speicher
Case "MilFit":
ausbildungNr = "1"
Case "Circuit training":
ausbildungNr = "2"
Case "Volleyball":
ausbildungNr = "3"
Case "Fußball":
ausbildungNr = "4"
Case "Sportliche Ertuechtigung":
ausbildungNr = "5"
Case "BFT":
ausbildungNr = "6"
Case "DSA":
ausbildungNr = "7"
Case "Schwimmen":
ausbildungNr = "8"
Case Else
MsgBox "Fehler"
End Select
Set sh = ThisWorkbook.Worksheets(ausbildungNr)
i = 0
topPos = 12
For Each v In sh.Range("M2:M100")
If Not v = "0" Then
Set frameCard = Controls.add("Forms.Frame.1", "frame" & i)
With frameCard
.Left = 144
.Top = topPos
.Width = 258
.Height = 72
.Caption = ""
.Zoom = 100
.SpecialEffect = 3
.BorderColor = &H80000012
End With
Set cardTitel = frameCard.Controls.add("Forms.Label.1", "cardTitel" & i, True)
With cardTitel
.Left = 8
.Top = 6
.Width = 126
.Height = 18
.ForeColor = &H8000000D
.Caption = v.Cells(, -10)
.FontBold = True
.FontSize = 12
End With
Set infoBtn = frameCard.Controls.add("Forms.CommandButton.1", "infoBtn" & i, True)
With infoBtn
.Left = 144
.Top = 36
.Width = 102
.Height = 24
.ForeColor = &HFFFFFF
.BackColor = &H8000000D
.Caption = v & " Plätze frei"
End With
Debug.Print "infoBtn" & i
Set ausLabel = frameCard.Controls.add("Forms.Label.1", "ausLabel", Visible)
With ausLabel
.Left = 12
.Top = 30
.Width = 42
.Height = 12
.Caption = "Ausbilder"
End With
Set ausbilderLabel = frameCard.Controls.add("Forms.Label.1", "ausbilderLabel", Visible)
With ausbilderLabel
.Left = 54
.Top = 30
.Width = 72
.Height = 12
.FontBold = True
.Caption = v.Cells(, -9)
End With
Set amLabel = frameCard.Controls.add("Forms.Label.1", "amLabel", Visible)
With amLabel
.Left = 12
.Top = 48
.Width = 24
.Height = 12
.Caption = "Am"
End With
Set datumLabel = frameCard.Controls.add("Forms.Label.1", "datumLabel", Visible)
With datumLabel
.Left = 54
.Top = 48
.Width = 72
.Height = 12
.FontBold = True
.Caption = v.Cells(, -8)
End With
Set infoLabel = frameCard.Controls.add("Forms.Label.1", "infoLabel", Visible)
With infoLabel
.Left = 222
.Top = 6
.Width = 24
.Height = 12
.FontBold = True
.Caption = "Info"
End With
topPos = frameCard.Top + frameCard.Height + 10
i = i + 1
End If
Next
ausbildungsfilter.Caption = ausbildungSuche.ausbildungCB.Value
Exit Sub
fehler: MsgBox "Das hat leider nicht geklappt."
Unload Me
End Sub
You need a class module beside the user form. Here is a sample of the mechanic how dynamic events works:
Place this code in the module of an empty user form:
Option Explicit
Dim comSampleBtn1 As clsClickEventsComBut
Dim comSampleBtn2 As clsClickEventsComBut
Private Sub UserForm_Initialize()
Dim comButTemp As MSForms.CommandButton
Dim commandButtonIndex As Byte
commandButtonIndex = 1
'Place sample button 1 and generate click event
Set comButTemp = Me.Controls.Add("Forms.commandbutton.1", "CommandButton" & commandButtonIndex, True)
commandButtonIndex = commandButtonIndex + 1
With comButTemp
'Place button
.Left = 50
.Top = 50
.Height = 20
.Width = 100
.Caption = "Sample Button 1"
.ControlTipText = "Click me"
End With
Set comSampleBtn1 = New clsClickEventsComBut
Set comSampleBtn1.ComButSample = comButTemp
Set comButTemp = Nothing
'Place sample button 2 and generate click event
Set comButTemp = Me.Controls.Add("Forms.commandbutton.1", "CommandButton" & commandButtonIndex, True)
commandButtonIndex = commandButtonIndex + 1
With comButTemp
'Place button
.Left = 50
.Top = 75
.Height = 20
.Width = 100
.Caption = "Sample Button 2"
.ControlTipText = "Click me too"
End With
Set comSampleBtn2 = New clsClickEventsComBut
Set comSampleBtn2.ComButSample = comButTemp
Set comButTemp = Nothing
End Sub
Now you need a class module with the name clsClickEventsComBut
Copy the following code to this module:
Option Explicit
Public WithEvents ComButSample As MSForms.CommandButton
Private Sub ComButSample_Click()
MsgBox "You clicked the sample button: " & UserForm1.ActiveControl.Name & Chr(13) & "With the caption: " & UserForm1.ActiveControl.Caption
End Sub
If you now click one of the two buttons, the message box will be show. This works with all controls.
Edit: New text for the message box with reference to the clicked button.
You have to assign this to the OnClick property of the button (usually on the OnLoad event or something similar):
infoBtn1.OnClick = "[Event Procedure]"
This assumes you have your Private Sub InfoBtn1_Click procedure declared like you have on your example code.
And note that it is this exact "[Event Procedure]" string that should be assigned to the OnClick.
Related
I create Userform
'Sub Crt_UserForm(ByVal count23 As Long, ByVal Temp As String, shts As Variant)
Dim myForm As Object
Dim Textbox1 As MSForms.TextBox
Dim Textbox2 As MSForms.TextBox
Dim Label1 As MSForms.Label
Dim Label2 As MSForms.Label
Dim Button1 As MSForms.CommandButton
Dim Button2 As MSForms.CommandButton
'Dim shtchk() As MSForms.CheckBox
Set myForm = ThisWorkbook.VBProject.VBComponents.Add(3)
'Set myForm = CallByName(UserForms, "Add", VbMethod, "Test")
ReDim shtchk(count23) As MSForms.CheckBox
With myForm
.Properties("Name") = "Test" 'Иногда эта строка вызывает ошибку
.Properties("Caption") = "Выберите листы для защиты паролем"
.Properties("Width") = 300
.Properties("Height") = 150
End With
'For Each x In Me.UserForms
'If x.Name = "Test" & a Then
'Next x
Set Label1 = Test.Controls.Add("Forms.Label.1", "Label1")
Set Label2 = Test.Controls.Add("Forms.Label.1", "Label2")
Set Textbox1 = Test.Controls.Add("Forms.Textbox.1", "Textbox1")
Set Textbox2 = Test.Controls.Add("Forms.Textbox.1", "Textbox2")
Set Button1 = Test.Controls.Add("Forms.CommandButton.1", "Button1")
Set Button2 = Test.Controls.Add("Forms.CommandButton.1", "Button2")
With Label1
.Top = 10
.Left = 10
.Width = 50
.Height = 20
.Caption = "Текущий пароль"
End With
With Label2
.Top = 10
.Left = 70
.Width = 50
.Height = 20
.Caption = "Новый пароль"
End With
With Textbox1
.Top = 40
.Left = 10
.Width = 50
.Height = 20
'.Caption = "Новый пароль"
End With
With Textbox2
.Top = 40
.Left = 70
.Width = 50
.Height = 20
'.Caption = "Новый пароль"
End With
With Button1
.Top = 70
.Left = 10
.Width = 50
.Height = 20
'.Caption = "Новый пароль"
End With
With Button2
.Top = 70
.Left = 70
.Width = 50
.Height = 20
'.Caption = "Новый пароль"
End With
Test.Show
End Sub
'
after the actions are over, I delete the created userform:
Sub RemoveUserForm()
With ThisWorkbook.VBProject.VBComponents
.Remove .item("Test")
End With
End Sub
First time it runs OK. But when I run it second time, it gives the error "Ambiguous name detected: Test" in the string:
Set Label1 = Test.Controls.Add("Forms.Label.1", "Label1")
So, somewhere deleted object myForm with the name "Test" is stored and prevents from creating the Userform object with the same name. How to fix it?
The solvation was in method of call to userform object via .Designer property Set Label1 = myForm.Designer.Controls.Add("Forms.Label.1", "Label1")
and method of userform show VBA.UserForms.Add(s).Show
Sub Crt_UserForm()
Dim myForm As Object
Dim s As String
Dim Textbox1 As MSForms.TextBox
Dim Textbox2 As MSForms.TextBox
Dim Label1 As MSForms.Label
Dim Label2 As MSForms.Label
Dim Button1 As MSForms.CommandButton
Dim Button2 As MSForms.CommandButton
Set myForm = ThisWorkbook.VBProject.VBComponents.Add(3)
With myForm
.Properties("Caption") = "Smth"
.Properties("Width") = 300
.Properties("Height") = 150
End With
s = myForm.Name
Set Label1 = myForm.Designer.Controls.Add("Forms.Label.1", "Label1")
Set Label2 = myForm.Designer.Controls.Add("Forms.Label.1", "Label2")
Set Textbox1 = myForm.Designer.Controls.Add("Forms.Textbox.1", "Textbox1")
Set Textbox2 = myForm.Designer.Controls.Add("Forms.Textbox.1", "Textbox2")
Set Button1 = myForm.Designer.Controls.Add("Forms.CommandButton.1", "Button1")
Set Button2 = myForm.Designer.Controls.Add("Forms.CommandButton.1", "Button2")
With Label1
.Top = 10
.Left = 10
.Width = 50
.Height = 20
.Caption = "SMTH"
End With
With Label2
.Top = 10
.Left = 70
.Width = 50
.Height = 20
.Caption = "SMTH"
End With
With Textbox1
.Top = 40
.Left = 10
.Width = 50
.Height = 20
End With
With Textbox2
.Top = 40
.Left = 70
.Width = 50
.Height = 20
'.Caption = "SMTH"
End With
With Button1
.Top = 70
.Left = 10
.Width = 50
.Height = 20
.Caption = "OK"
End With
With Button2
.Top = 70
.Left = 70
.Width = 50
.Height = 20
.Caption = "SMTH"
End With
With myForm.CodeModule
x = .CountOfLines
.InsertLines x + 1, "Sub Button1_Click()"
.InsertLines x + 2, "MsgBox ""Hello!"""
.InsertLines x + 3, "Unload Me"
.InsertLines x + 5, "End Sub"
End With
VBA.UserForms.Add(s).Show
ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=myForm
End Sub
I'm using a form to generate 3 groups of textboxes at run time. I'm trying to achieve this: when the user click a textbox of the group "txtboxe", a FileDialog opens so the user can choose the file. When the file is picked, i wwant to get the filepath.
The problem is, usually, i would use a sub like - textboxe_Click - but i need this to work inside a existing module, and the name of each textbox is generate at run time.
So... Any ideas? I tried to use multiple times something with 'Controls' commands, but without any sucess. I manage to pick the data from each textbox, but not to control a click or change on a textbox group.
I'm providing the code below.
Dim i As Long
Dim o As Long
Dim number As Long
number = InputBox("How many docs?", "Number of docs")
Dim txtB1 As Control
Dim txtB2 As Control
For i = 1 To number
Set txtB1 = Controls.Add("Forms.Textbox.1")
With txtB1
.Name = "txtbox" & i
.Height = 16
.Width = 30
.Left = 60
.Top = 20 + (i * 40)
.Value = i
.Locked = True
.BackColor = &H80000000
End With
Set txtB2 = Controls.Add("Forms.Textbox.1")
With txtB2
.Name = "txtboxw" & i
.Height = 18
.Width = 234
.Left = 162
.Top = 20 + (i * 40)
Debug.Print .Name
End With
Set txtB3 = Controls.Add("Forms.Textbox.1")
With txtB3
.Name = "txtboxe" & i
.Height = 18
.Width = 264
.Left = 420
.Top = 20 + (i * 40)
Debug.Print .Name
End With
Next i
End Sub
Private Sub CommandButton3_Click()
Dim p As Long
For p = 1 To number
cells(p + 1, 1) = Controls("txtbox" & p).Value
cells(p + 1, 2) = Controls("txtboxw" & p).Value
cells(p + 1, 3) = Controls("txtboxe" & p).Value
Next p
End Sub ````
Registering event handlers with dynamically created controls is tricky.
But you can do it using a Class Module and WithEvent variable.
First, add the following code as a Class Module ControlEvent.
Option Explicit
Private WithEvents targetCtrl As MSForms.TextBox
Public Sub SetCtrl(new_ctrl As MSForms.TextBox)
Set targetCtrl = new_ctrl
End Sub
' You can add arbitrary event handlers for TextBox as ``targetCtrl_(Event handler name)``
Private Sub targetCtrl_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
With Application.FileDialog(msoFileDialogFilePicker)
If .Show() Then
' You can access the control with the targetCtrl class variable
targetCtrl.Value = .SelectedItems(1)
End If
End With
End Sub
Then, modify your code in the UserForm to the following.
I added an array ctrls to store the ControlEvent class instances and set the created controls to the WithEvents class variables with SetCtrl method.
Private ctrls As Variant ' Added
Sub CommandButton2_Click()
Dim i As Long
Dim o As Long
Dim number As Long
number = InputBox("How many docs?", "Number of docs")
Dim txtB1 As Control
Dim txtB2 As Control
Dim txtB3 As Control
ReDim ctrls(0 To number - 1)
For i = 1 To number
Set txtB1 = Controls.Add("Forms.Textbox.1")
With txtB1
.Name = "txtbox" & i
.Height = 16
.Width = 30
.Left = 60
.Top = 20 + (i * 40)
.Value = i
.Locked = True
.BackColor = &H80000000
End With
Set txtB2 = Controls.Add("Forms.Textbox.1")
With txtB2
.Name = "txtboxw" & i
.Height = 18
.Width = 234
.Left = 162
.Top = 20 + (i * 40)
Debug.Print .Name
End With
Set txtB3 = Controls.Add("Forms.Textbox.1")
With txtB3
.Name = "txtboxe" & i
.Height = 18
.Width = 264
.Left = 420
.Top = 20 + (i * 40)
Debug.Print .Name
End With
Set ctrls(i - 1) = New ControlEvent ' Added
ctrls(i - 1).SetCtrl txtB3 ' Added
Next i
End Sub
I created many buttons dynamically (creating schedule) and want all of them do the same thing during Click event (OnClick property).
Of course, I can create max number of buttons on the form beforehand and set them invisible, and so forth, while adding "call SomeEvent" on their Click event considering that there can be over a thousand buttons. This would be very tedious.
Therefore, simplified:
I created new class btnClass`
Public WithEvents ButtonEvent As MsForms.CommandButton
Private Sub ButtonEvent_Click()
MsgBox "hey"
End Sub
Then, in my UserForm, where I dynamically create buttons I added this (I also have Collection, to remove buttons later), in its simplified form:
Dim btnColl As Collection
Dim Buttons As New btnClass
Set btnColl = New Collection
Set Buttons = New btnClass
For i = 0 To btnCount
Set theButton = Controls.Add("Forms.CommandButton.1", "btn" & i, True)
With theButton
.Height = 17
.Caption = "btn" & i
End With
Set Buttons.ButtonEvent = theButton
btnColl.Add theButton, theButton.Name
Next i
But nothing happens when I click dynamically created buttons. What am I missing?
---UPDATED
---#FaneDuru Provided solution which worked for me
ReDim Buttons(0 To btnCount, 0 To dtDiff)
For labelcounter = 0 To dtDiff 'add date labels
Set theLabel = Controls.Add("Forms.Label.1", "lblDay" & labelcounter, True)
With theLabel
.Caption = VBA.Format(DateAdd("d", labelcounter, bDate), "d-mm-yy")
.Left = 15 + 44 * labelcounter
.BackColor = vbBlack
.Font.Bold = True
.ForeColor = vbWhite
.Height = 13
.Width = 40
.Top = 85
End With
For i = 0 To btnCount 'add time buttons
pTime = DateAdd("n", i * dur, begTime)
Set theButton = Controls.Add("Forms.CommandButton.1", "btn" & CDate(theLabel.Caption & " " & TimeValue(pTime)), True)
With theButton
.Height = 17
.Caption = VBA.Format(TimeValue(pTime), "hh:mm")
'.Caption = CDate(theLabel.Caption & " " & TimeValue(pTime))
.Left = 15 + 44 * labelcounter
.BackColor = vbGreen
.Width = 40
.Top = 100 + 18 * i
End With
Set Buttons(i, labelcounter).ButtonEvent = theButton
btnColl.Add theButton, theButton.Name
Next i
Next labelcounter
In this way, only for the last created button an event is allocated. You must declare an array of classes... I also played a little with the Left property of the newly created buttons, only to have the possibility to test their click event. Try the next approach, please:
Option Explicit
Private btnColl As New Collection
Dim Buttons() As New btnClass
Private Sub btCreate_Click()
Dim btnCount As Long, theButton As CommandButton, i As Long
btnCount = 3
ReDim Buttons(0 To btnCount)
For i = 0 To btnCount
Set theButton = Me.Controls.aDD("Forms.CommandButton.1", "btn" & i, True)
With theButton
.height = 17
.Caption = "btn" & i
.left = 50 * i
End With
btnColl.aDD theButton, theButton.Name
Set Buttons(i).ButtonEvent = theButton
Next i
End Sub
Private Sub btdelete_Click() 'buttons deletion...
Dim i As Long
For i = 1 To btnColl.count
Me.Controls.Remove (btnColl(i).Name)
Next
End Sub
I have a userform with various checkboxes. Each checkbox when selected opens up a new userform with a new set of checkbox, textbox and spinbutton controls based on a column in a worksheet. This column will change and thus there will be a new number of checkboxes, textbox and spinbutton controls every time the macro runs.
I need to use the spinbutton_change() event to set the value of the textbox. Since I don't know the number of spinbuttons that will exist at a given time how can I code this so each spinbutton updates its respective textbox?
Private Sub UserForm_Activate()
Dim NewChkBx As MSForms.CheckBox
Dim NewTxtBx As MSForms.TextBox
Dim NewSpinButton As MSForms.SpinButton
Dim rngSource As Range
Dim rngCell As Range
Dim TopPos As Integer
Dim MaxWidth As Long
Sheets("Background").UsedRange.ClearContents
'Filters items in Col A which Equal "Light"
Application.ScreenUpdating = False
Worksheets("Weight_Data").Unprotect
Worksheets("Background").[a1].CurrentRegion.Offset(1).ClearContents
Worksheets("Weight_Data").Range("D1:D1000").AutoFilter 1, "Light"
Worksheets("Weight_Data").Range("A2:H1000").Copy (Worksheets("Background").Range("A65536").End(xlUp)(2))
Worksheets("Weight_Data").Range("A1").AutoFilter 'Turn Filter Off
' End of filter
' Start of creating new userform based only on checked boxes.
With Worksheets("Background")
Set rngSource = Worksheets("Background").Range("B2", .Cells(.Rows.Count, "B").End(xlUp))
End With
TopPos = 5
MaxWidth = 0
For Each rngCell In rngSource
If rngCell.Value <> "" Then
Set NewChkBx = Me.Controls.Add("Forms.CheckBox.1")
Set NewTxtBox = Me.Controls.Add("Forms.Textbox.1")
Set NewSpinButton = Me.Controls.Add("Forms.Spinbutton.1")
With NewChkBx
.Caption = rngCell.Value
.Left = 5
.Top = TopPos
.AutoSize = True
If .width > MaxWidth Then MaxWidth = .width
End With
With NewTxtBox
.Enabled = True
.Value = 0
.Enabled = False
.Text = 0
.Height = 15
.width = 20
.Left = NewChkBx.width + 20
.Top = TopPos
.AutoSize = True
If .width > MaxWidth Then MaxWidth = .width
End With
With NewSpinButton
.Value = 0
.Height = 15
.width = 10
.Left = NewTxtBox.width + NewChkBx.width + 20
.Top = TopPos
If .width > MaxWidth Then MaxWidth = .width
End With
TopPos = TopPos + 60
End If
Next rngCell
Me.width = MaxWidth + 60
Me.Height = TopPos + 25
' Worksheets("Weight_Data").Protect
Application.ScreenUpdating = True
Sheets("Background").UsedRange.ClearContents
End Sub
Here's a slightly-simplified version of your code which has some dynamic event capture built in.
Userform:
Option Explicit
Dim col As Collection '<<< needs to be global
Private Sub UserForm_Activate()
Dim x As Long, TopPos As Long, MaxWidth As Long
Dim NewChkBx As MSForms.CheckBox
Dim NewTxtBox As MSForms.TextBox
Dim NewSpinButton As MSForms.SpinButton
Set col = New Collection
TopPos = 5
MaxWidth = 0
For x = 1 To 10
Set NewChkBx = Me.Controls.Add("Forms.CheckBox.1")
Set NewTxtBox = Me.Controls.Add("Forms.Textbox.1")
Set NewSpinButton = Me.Controls.Add("Forms.Spinbutton.1")
With NewChkBx
.Caption = "Number " & x
.Left = 5
.top = TopPos
.AutoSize = True
If .Width > MaxWidth Then MaxWidth = .Width
End With
With NewTxtBox
.Enabled = True
.Value = 0
.Enabled = False
.Text = 0
.Height = 15
.Width = 20
.Left = NewChkBx.Width + 20
.top = TopPos
.AutoSize = True
If .Width > MaxWidth Then MaxWidth = .Width
End With
With NewSpinButton
.Value = 0
.Height = 15
.Width = 10
.Left = NewTxtBox.Width + NewChkBx.Width + 20
.top = TopPos
If .Width > MaxWidth Then MaxWidth = .Width
End With
col.Add CaptureEvents(NewSpinButton, NewTxtBox) '<<< save new class instance
TopPos = TopPos + 20
Next x
Me.Width = MaxWidth + 60
Me.Height = TopPos + 25
End Sub
'Return a new instance of clsEvents with controls added....
Private Function CaptureEvents(spn As MSForms.SpinButton, txt As MSForms.TextBox)
Dim rv As New clsEvents
Set rv.spn = spn
Set rv.tb = txt
Set CaptureEvents = rv
End Function
Class module "clsEvents":
Option Explicit
Public WithEvents spn As MSForms.SpinButton
Public tb As MSForms.TextBox
Private Sub spn_Change()
Me.tb.Text = spn.Value
End Sub
i've got dynamically generated userform consisting of labels, checkboxes and text boxes. is it possible to have a contents of a textbox selected when clicked?
this is method i'm using to create textbox:
Set NewTextBox = MainFrame.Controls.Add("Forms.TextBox.1")
With NewTextBox
.Name = "QtyTB" & row
.Value = Cells(cellrow - 1 + row, 11)
.Height = 18
.Left = 210
.Top = 18
.Width = 36
.Enabled = True
.BackColor = RGB(255, 255, 0)
End With
if i was to create textbox manually i could write on_click sub for specific text box. but as i said, code generates everything from scratch.
so if there is a property, or some other way to get it done, i would be gratefull.
Yes, this can be done by creating a class module with event handling
The following code will need a bit of adaption as there isn't much code to go on in the question...
In a class module called TextBoxEventHandler
Private WithEvents FormTextBox As MSForms.TextBox
Public Property Set TextBox(ByVal oTextBox As MSForms.TextBox)
Set FormTextBox = oTextBox
End Property
Private Sub FormTextBox_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Button = 1 Then
With FormTextBox
.SelStart = 0
.SelLength = Len(.Text)
End With
End If
End Sub
Then in the UserForm code
Private CollectionOfEventHandlers As Collection
Private Sub UserForm_Initialize()
Dim i As Long
Dim NewTextBox As MSForms.TextBox
For i = 0 To 4
Set NewTextBox = Me.Controls.Add("Forms.TextBox.1")
With NewTextBox
.Name = "QtyTB" & i ' Row
.Value = "Text " & i ' Cells(cellrow - 1 + Row, 11)
.Height = 18
.Left = 21
.Top = 18 + i * 25
.Width = 36
.Enabled = True
.BackColor = RGB(255, 255, 0)
End With
Next i
Call InitialiseHandlers
End Sub
Private Function InitialiseHandlers()
Set CollectionOfEventHandlers = New Collection
Dim FormControl As Control
For Each FormControl In Me.Controls
If TypeName(FormControl) = "TextBox" Then
Dim EventHandler As TextboxEventHandler
Set EventHandler = New TextboxEventHandler
Set EventHandler.TextBox = FormControl
CollectionOfEventHandlers.Add EventHandler
End If
Next FormControl
End Function