Change event for multiple text boxes - vba

I have written single change event for multiple text boxes using class Module but what I observed is in my 'oControl' Me.Controls give False and not the control. Is there any other way I can do that?
Private m_oCollectionOfEventHandlers As Collection
Private Sub UserForm_Initialize()
Set m_oCollectionOfEventHandlers = New Collection
Dim oControl As Control
For Each oControl In Me.Controls
If TypeName(oControl) = "TextBox" Then
Dim oEventHandler As Class1
Set oEventHandler = New Class1
Set oEventHandler.TextBox = oControl
m_oCollectionOfEventHandlers.Add oEventHandler
End If
Next oControl
End Sub
'CLASS MODULE
Private WithEvents m_oTextBox As TextBox
Public Property Set TextBox(ByVal oTextBox As TextBox)
Set m_oTextBox = oTextBox
End Property
Private Sub m_oTextBox_Change()
MsgBox ("Hello")
End Sub

Related

Passing a variable from class module to userform

Hej,
I am trying to design a code, where a number of commandbuttons call the same userform. I have created the class module and got it to work so that they all call the userform, but I need the name of the button passed on from the class module into the userform initialize. I have tried it with property get and a public function, but can't get it to work. The variable I want to pass is the "ScreenShotCap" as string Anyone, who can help?
CLASS MODULE CODE
Option Explicit
Public ScreenShotCap As String
Public WithEvents CmdBtn As MSForms.CommandButton
Property Set obj(btns As MSForms.CommandButton)
'Defines the property of the object called
Set CmdBtn = btns
End Property
Private Sub CmdBtn_Click()
'Gets the button caption
ScreenShotCap = CmdBtn.Name
'Loads the userform
ufScreenshot.Show
End Sub
USERFORM CODE
Private Sub UserForm_Initialize()
Dim btnNo As Variant
Dim imNo1, imNo2, imNo3 As Integer
'Gets the number of the button
btnNo = Right(ScreenShotCap, 1)
'Sets the image number
imNo1 = Int(btnNo + 2)
imNo2 = Int(btnNo + 3)
imNo3 = Int(btnNo + 4)
'Loads the image from MSForms into userform
If ScreenShotCap = Worksheets("SW_TEST").OLEObjects("CommandButton1").Name Then
Application.ScreenUpdating = False
Me.Image1.Picture = Worksheets("SW_TEST").OLEObjects("Image1").Object.Picture
Me.Image2.Picture = Worksheets("SW_TEST").OLEObjects("Image2").Object.Picture
Me.Image3.Picture = Worksheets("SW_TEST").OLEObjects("Image3").Object.Picture
Application.ScreenUpdating = True
Else
Application.ScreenUpdating = False
Me.Image1.Picture = Worksheets("SW_TEST").OLEObjects("Image" & imNo1).Object.Picture
Me.Image2.Picture = Worksheets("SW_TEST").OLEObjects("Image" & imNo2).Object.Picture
Me.Image3.Picture = Worksheets("SW_TEST").OLEObjects("Image" & imNo3).Object.Picture
'after any change vba has to be told to refresh the UserForm for the change to appear
Me.Repaint
Application.ScreenUpdating = True
End If
End Sub
Move the codes in UserForm_Initialize() to a new sub with a parameter or just rename it to:
Public Sub LoadButtonImage(ScreenShotCap As String)
Then in your CmdBtn_Click() sub:
Load ufScreenshot.Show
ufScreenshot.LoadButtonImage CmdBtn.Name
uScreenshot.Show

Updating the text on a dynamically generated control In VB

I have a dynamically generated TabControl, and am trying to update a Combobox in the TabPage. The function that updates the Combobox is called of a click event.
I've tried to follow some guides regarding manipulating dynamically generated controls by storing the dynamically generated controls as properties on the class: How to pass value from one form to another form's dynamically created control
The controls are generated dynamically as such:
Public Class Form1
Public Sub loadForm()
Dim ctp As New CustomTabPage("Tab number" & i, ErrorList(i), myList, New Object)
Me.myTabControl.TabPages.Add(ctp)
...
End Sub
End Class
Public Class CustomTabPage
Inherits TabPage
Private m_testSelect As ComboBox
...
Public Property testSelect() As ComboBox
Get
testSelect = m_testSelect
End Get
Set(ByVal mytestSelect As ComboBox)
m_testSelect = mytestSelect
End Set
End Property
Public Sub newTab()
m_testSelect = New ComboBox
With m_testSelect
.Location = New System.Drawing.Point(locX + labelSize, locY)
End With
Me.Controls.Add(m_testSelect)
Dim ccb As New CustomCheckBox()
Me.Controls.Add(m_testSelect)
End Sub
Public Sub UpdateCBOs(ByVal i As Integer)
If i = 1 Then
testSelect.Text = "Test1"
ElseIf i = 0 Then
testSelect.Text = "Test2"
End If
...
End Sub
End Class
Public Class CustomCheckBox
Inherits CheckBox
Public Sub Clicked(sender As Object, e As EventArgs) Handles MyBase.CheckedChanged
Dim ctp = CType(Form1.myTabControl.SelectedTab, CustomTabPage)
ctp.UpdateCBOs(i)
End Sub
End Class
Currently while debugging through I stop on the line after line
errorBy.Text = "Test1"
When I mouse over errorBy.Text, and see that errorBy.Text ="" and indeed after the click event finishes, I see on the form that the combobox is not updated.

Handling custom events using modeless form & user defined classes

I'm trying to display the progress of various routines on a modeless form, by having those routines raise custom events detailing their progress. The form should handle those events to display appropriate information.
The problem is that although RaiseEvent is called, the event handlers don't then do anything.
The intended result of the following code is the two debug.prints would be called whenever an event is raised by triggerTest.
The only success I've had is with raising the error within the userform, by CommandButton1_Click in the following code. The form's event handler then kicks in (rather redundantly, but perhaps that means I'm on the right path).
Thanks
Event class clsChangeProgressTrigger
Option Explicit
Public Enum geProgressStatus
geProgressStatusComplete = -1
geProgressStatusRestart = -2
End Enum
Public Event ChangeProgress(dProgress As Double, sProcedure As String)
'
Public Sub Update(dProgress As Double, sProcedure As String)
RaiseEvent ChangeProgress(dProgress, sProcedure)
End Sub
Public Sub Complete(sProcedure As String)
RaiseEvent ChangeProgress(geProgressStatusComplete, sProcedure)
End Sub
Public Sub Restart(sProcedure As String)
RaiseEvent ChangeProgress(geProgressStatusRestart, sProcedure)
End Sub
User form frmOutput
Option Explicit
Private WithEvents mProgressTrigger As clsChangeProgressTrigger
'
Private Sub CommandButton1_Click()
Call mProgressTrigger.Update(12.34, "SomeValue")
End Sub
Private Sub CommandButton2_Click()
Call modZTest.triggerTest
End Sub
Private Sub UserForm_Initialize()
Set mProgressTrigger = New clsChangeProgressTrigger
End Sub
Private Sub mProgressTrigger_ChangeProgress(dProgress As Double, sProcedure As String)
Debug.Print "Form Event Handled"
End Sub
Event test class clsEventTest
Option Explicit
Private WithEvents mProgressTrigger As clsChangeProgressTrigger
'
Private Sub mProgressTrigger_ChangeProgress(dProgress As Double, sProcedure As String)
Debug.Print "Class Event Handled"
End Sub
Private Sub Class_Initialize()
Set mProgressTrigger = New clsChangeProgressTrigger
End Sub
Test wrapper in public module modZTest
Public Sub triggerTest()
Application.EnableEvents = True
' Instantiate Trigger class for this routine
' Dim cChangeProgressTrigger As clsChangeProgressTrigger
Set gChangeProgressTrigger = New clsChangeProgressTrigger
' Instantiate Event Test class, which should handle raised event
Dim cEventTest As clsEventTest
Set cEventTest = New clsEventTest
' Instantiate user form, which should handle raised event
Set gfrmOutput = New frmOutput ' Modeless form, gfrmOutput has global scope
gfrmOutput.Show
Stop
' Raise an event
Call gChangeProgressTrigger.Complete("SomeValue")
' Tidy Up
Set gfrmOutput = Nothing
Set gChangeProgressTrigger = Nothing
Set cEventTest = Nothing
End Sub
Thanks Dee, that helped me along to the solution.
With this declared as global scope:
Public gChangeProgressTrigger As clsChangeProgressTrigger
I had to change the class / form level initialisations as follows:
Private Sub UserForm_Initialize()
' Set mProgressTrigger = New clsChangeProgressTrigger ' Old
Set mProgressTrigger = gChangeProgressTrigger ' New
End Sub
and
Private Sub Class_Initialize()
' Set mProgressTrigger = New clsChangeProgressTrigger ' Old
Set mProgressTrigger = gChangeProgressTrigger ' New
End Sub
Then the event handlers fired as desired.

General function for opening ChildWinforms using reflection?

I'm not sure how to put this so the title may seem a little strange. I have a VB.NET MDI Winform application. In this app when I click a menuitem a child window is opened. To handle what child window must be opened I have case statement in my ToolStripMenuItem_Click event. The problem is that in every case-item the code is nearly the same. So I was wondering if it would be possible to have a general function so the code becomes more readable.
Example:
Case "mnuPrint"
Dim ChildWindowFound As Boolean = False
If Not (MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In MdiChildren
If ChildWindow.Name.Equals("Form1") Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
If Not ChildWindowFound Then
Dim childForm As New Form1()
childForm.Name = "Form1"
childForm.MdiParent = Me
childForm.Show()
End If
Case "mnuSearch"
Dim ChildWindowFound As Boolean = False
If Not (MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In MdiChildren
If ChildWindow.Name.Equals("Form2") Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
If Not ChildWindowFound Then
Dim childForm As New Form2()
childForm.Name = "Form2"
childForm.MdiParent = Me
childForm.Show()
End If
As you can see the code is nearly the same but with different forms, here Form1 and Form2 which are different, but it can be many different forms of course. The function I'm talking about would look something like:
Public Sub OpenNewForm(ByVal frm As Form, ByVal parent As Form, ByVal singleInstance As Boolean)
Dim ChildWindowFound As Boolean = False
If Not (parent.MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In parent.MdiChildren
If ChildWindow.Name.Equals(frm.Name) Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
If Not ChildWindowFound Then
Dim childForm As New Form
childForm.Name = frm.Name
childForm.MdiParent = Me
childForm.Show()
End If
End Sub
This doesn't work because I pass the parameters (first two) as Form-type, where it should be Form1 and ParentForm for example, not Form. I think it is possible, just don't know where to start. May be using reflection or something?
UPDATE:
Based on the answers given I came up with this code which is working fine:
'Code contributed by Rod Paddock (Dash Point Software)
'www.dashpoint.com
'Dim oForm As Form = ObjectFactory.CreateAnObject("MyApplication.frmTwo")
'oForm.Show()
Public Shared Function CreateAnObject(ByVal ObjectName As String) As Object
Dim Assem = [Assembly].GetExecutingAssembly()
Dim myType As Type = Assem.GetType(ObjectName.Trim)
Dim o As Object = Nothing
Try
o = Activator.CreateInstance(myType)
Catch oEx As TargetInvocationException
MessageBox.Show(oEx.ToString)
End Try
Return o
End Function
Public Shared Sub ActivateChildWindow(ByVal frmName As String, ByRef ParentMDIWindow As Form)
Dim ChildWindowFound As Boolean = False
With ParentMDIWindow
If Not (.MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In .MdiChildren
If ChildWindow.Name.Equals(frmName) Then
ChildWindow.Activate()
ChildWindowFound = True
End If
Next
End If
End With
If Not ChildWindowFound Then
Dim childForm As Form = CreateAnObject(frmName)
childForm.Name = frmName
childForm.MdiParent = ParentMDIWindow
childForm.Show()
End If
Maybe something like this can help you:
Dim myForm As Form = Nothing
Dim FormName As String = String.Empty
Dim formType As Type
Select Case Options
Case "mnuPrint"
FormName = "Form1"
myForm = getWindowByName(FormName)
Case "mnuSearch"
FormName = "Form2"
myForm = getWindowByName(FormName)
End Select
If myForm Is Nothing Then
formType = Type.GetType("WindowsApplication2." + FormName) 'WindowsApplication2 is my project's name
myForm = Activator.CreateInstance(formType)
myForm.Name = FormName
myForm.MdiParent = Me
myForm.Show()
Else
myForm.Activate()
End If
And the function:
Function getWindowByName(ByVal FormName As String) As Form
Dim frm As Form = Nothing
If Not (MdiChildren.Length.Equals(0)) Then
For Each ChildWindow As Form In MdiChildren
If ChildWindow.Name.Equals(FormName) Then
frm = ChildWindow
End If
Next
End If
Return frm
End Function
See if this will get you started. Create a project with three forms, form1 with two buttons on. Then, add this code to Form1:
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click, Button2.Click
Dim t As Type
Select Case sender.name
Case "Button1"
t = GetType(Form2)
Case "Button2"
t = GetType(Form3)
End Select
Dim f = System.Activator.CreateInstance(t)
f.show()
End Sub
End Class

Programmatically adding a commandbutton to a userform

In excel vba I have added a commandbutton to userform... like below
Set ctrl = Me.Controls.Add( _
bstrProgID:="Forms.CommandButton.1", _
Name:="CommandButton1", Visible:=True)
Now I wanted to know how would I tell it what to do when it is clicked?
This is one of those techniques that vba will let you do, but you probably shouldn't. For all the same reasons you shouldn't use code that alters your code.
That said, here is how to do what you want. First insert a class module and name it DynBtn, then paste this code into it:
Private WithEvents mobjBtn As MSForms.CommandButton
Private msOnAction As String
''// This has to be generic or call by name won't be able to find the methods
''// in your form.
Private mobjParent As Object
Public Property Get Object() As MSForms.CommandButton
Set Object = mobjBtn
End Property
Public Function Load(ByVal parentFormName As Object, ByVal btn As MSForms.CommandButton, ByVal procedure As String) As DynBtn
Set mobjParent = parentFormName
Set mobjBtn = btn
msOnAction = procedure
Set Load = Me
End Function
Private Sub Class_Terminate()
Set mobjParent = Nothing
Set mobjBtn = Nothing
End Sub
Private Sub mobjBtn_Click()
CallByName mobjParent, msOnAction, VbMethod
End Sub
Now to use this in your form, create a blank user form and paste this code into it:
Private Const mcsCmdBtn As String = "Forms.CommandButton.1"
Private mBtn() As DynBtn
Private Sub UserForm_Initialize()
Dim i As Long
ReDim mBtn(1) As DynBtn
For i = 0 To UBound(mBtn)
Set mBtn(i) = New DynBtn
Next
''// One Liner
mBtn(0).Load(Me, Me.Controls.Add(mcsCmdBtn, "Btn1", True), "DoSomething").Object.Caption = "Test 1"
''// Or using with block.
With mBtn(1).Load(Me, Me.Controls.Add(mcsCmdBtn, "Btn2", True), "DoSomethingElse").Object
.Caption = "Test 2"
.Top = .Height + 10
End With
End Sub
Public Sub DoSomething()
MsgBox "It Worked!"
End Sub
Public Sub DoSomethingElse()
MsgBox "Yay!"
End Sub
Private Sub UserForm_Terminate()
Erase mBtn
End Sub