Access VBA put a form element name as an argument - vba

Let's see if anyone knows how to solve this problem:
I have a form with several elements: Some of them are textboxes called A1, A2, A3, A4...
Now, their AfterUpdate SubProcedure is extremely long but barely similar for each of them: A1_AfterUpdate, A2_AfterUpdate, A3_AfterUpdate...etc... are very similar but for the names of the textboxes they change.
My idea was to gather all that was equal in a subprocedure defined this way:
Private Sub Update(Box As String, Menu As Boolean)
If Menu=True{
Me!Box.Text = "This is the text that is going to change"
}
End Sub
So, the only thing I must do is to call it this way, for instance:
Update(A1, True)
But it doesn't seems to work. Any idea on how to reach this objective?

Add a class module - I've called it clsTextBoxEvents.
Add this code to the class:
Public WithEvents txt As Access.TextBox
Private Sub txt_AfterUpdate()
MsgBox txt.Name & " has been updated."
End Sub
In your form module add this code:
Public MyTextBoxes As New Collection
Private Sub Form_Open(Cancel As Integer)
Dim ctl As Control
Dim txtBoxEvent As clsTextBoxEvents
For Each ctl In Me.Controls
If TypeName(ctl) = "TextBox" Then
Set txtBoxEvent = New clsTextBoxEvents
Set txtBoxEvent.txt = ctl
txtBoxEvent.txt.AfterUpdate = "[Event Procedure]"
MyTextBoxes.Add txtBoxEvent
End If
Next ctl
End Sub
The MyTextBoxes declaration must be at the very top of the module.
This just adds the AfterUpdate event to all textboxes on the form. You'll probably want to refine that a bit to textboxes with specific text in the name, or controls that are in a specific frame on the form.

If you use a function instead of a sub:
Private Function UpdateCtl(Menu As Boolean)
If Menu Then
activecontrol = "This is the text that is going to change"
End If
End Sub
then you can call it directly from the control's AfterUpdate property: =UpdateCtl(True).
Simple and fast

Related

VBA Input Value From Another UserFormB into TextBox From UserFormA

I have a userForm (mappingGuide) that allows user to pick a smartyTag from a list of more user-friendly names.
I have a second user-form (conditionalBuilder) that I would like to call this userForm upon double-clicking a text field so that a user can lookup which smartyTag to apply (in case they don't know).
So logic, is:
open conditionalBuilder
double-click Field text box
mappingGuide opens
pick a smartytag from listbox
fill smartytag value into field text-box in conditionalBuilder
unload mappingGuide
The issue I think I having with completing the requirement is that when I load the forms themselves I cannot find a way to set the text of the fieldName textbox of the loaded instance of conditionalBuilder (see last code block below). I've been searching around, but cannot figure it out.
Here is relevant code:
conditionalBuilder loads from Custom UI ribbon
Sub RunCode(ByVal Control As IRibbonControl)
Select Case Control.ID
Case Is = "mapper": LoadMappingGuide
Case Is = "conditional": LoadConditionalBuilder
End Select
End Sub
Sub LoadConditionalBuilder()
Dim conditionalForm As New conditionalBuilder
conditionalForm.Show False
End Sub
double-click event of fieldName then loads mappingGuide
Private Sub fieldName_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Me.hide
Dim pickField As New mappingGuide
pickField.Show False
End Sub
smartTag listbox click event then attempts to place selection into fieldName (or selection if form not loaded)
Private Sub smartTagList_Click()
If smartTagList.ListIndex > -1 And smartTagList.Selected(smartTagList.ListIndex) Then
Dim smartyTag As String
smartyTag = smartTagList.List(smartTagList.ListIndex, 2)
If isUserFormLoaded(conditionalBuilder.Name) Then
'*** ---> below is my issue how to reference instance of form
conditionalBuilder.fieldName.Text = smartyTag
conditionalBuilder.Show
Else
Selection.Range.Text = smartyTag
End If
End If
Unload Me
End Sub
If there is a better set-up that would be great to know too. I have the forms separate because there's a couple of levels a user can create tags with.
This is how I would do it, a bit of overkill but in case of multiple forms it will be beneficial.
Module 1:
Option Explicit
Sub test()
frmMaster.Show False
End Sub
Form 1 : frmMaster:
Option Explicit
'/ Declare with events
Dim WithEvents frmCh As frmChild
Private Sub TextBox1_DblClick(ByVal cancel As MSForms.ReturnBoolean)
handleDoubleClick
End Sub
Sub handleDoubleClick()
If frmCh Is Nothing Then
Set frmCh = New frmChild
End If
frmCh.Show False
End Sub
'/ Handle the event
Private Sub frmCh_cClicked(cancel As Boolean)
Me.TextBox1.Text = frmCh.bChecked
End Sub
Form 2: frmChild:
Option Explicit
Event cClicked(cancel As Boolean)
Private m_bbChecked As Boolean
Public Property Get bChecked() As Boolean
bChecked = m_bbChecked
End Property
Public Property Let bChecked(ByVal bNewValue As Boolean)
m_bbChecked = bNewValue
End Property
Private Sub CheckBox1_Click()
Me.bChecked = Me.CheckBox1.Value
'/ Raise an event when something happens.
'/ Caller will handle it.
RaiseEvent cClicked(False)
End Sub
You can do this with a presenter class which controls userform instances and pass values between them. I mocked up something similar to give you an idea.
Presenter. This is a class module which creates the userforms, controls their scope, and catches the event thrown by the
ConditionalBuilder. It makes it super easy to pass values between
userforms.
Private WithEvents CB As ConditionalBuilder
Private MG As MappingGuide
Public Sub ShowCB()
Set CB = New ConditionalBuilder
CB.Show vbModal
End Sub
Private Sub CB_ShowMappingGuide()
Set MG = New MappingGuide
MG.Show vbModal
CB.UpdateTB1 Value:=MG.SmartTag
End Sub
ConditionalBuilder.
This has a simple function to update your textbox and also an event which raises actions in the presenter.
Public Event ShowMappingGuide()
Public Function UpdateTB1(Value As String)
TextBox1.Value = Value
End Function
Private Sub TextBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
RaiseEvent ShowMappingGuide
End Sub
MappingGuide.
The Type and Property could be overkill since we just want one value from the mapping guide but it's still good practice.
Private Type TView
Tag As String
End Type
Private this As TView
Public Property Get SmartTag() As String
SmartTag = this.Tag
End Property
Private Sub UserForm_Initialize()
Tags.List = Array("a", "b", "c")
End Sub
Private Sub Tags_Click()
this.Tag = Tags.List(Tags.ListIndex, 0)
Me.Hide
End Sub
I have one final Standard Module which creates the Presenter. This is what you'd hook up to your ribbon.
Public Sub ShowProject()
With New Presenter
.ShowCB
End With
End Sub
Step 1 (double click text field)
Step 2 (selecting "b")
Step 3 (result)
I actually solved it by placing the below block inside the IF where I check for the form being loaded and I will leave open for better answers, if there are any.
Dim uForm As Object
For Each uForm In VBA.UserForms
If uForm.Name = conditionalBuilder.Name Then
uForm.fieldName.Text = smartyTag
uForm.Show
End If
Next

Function to clear UserForms checkbox in VBA

I am creating a program which has several UserForms.
At the end of the program I need to clear every Checkbox inside some UserForm. I have created a Function, but it cannot recognise which UserForm it should clear, can you help me there? Here is the code:
Function ClearUserForm(ByVal userf As String)
Dim contr As Control
For Each contr In userf.Controls
If TypeName(contr) = "CheckBox" Then
contr.Value = False
End If
Next
End Function
And I am calling the function like this, for example:
ClearUserForm ("UserForm2")
It seems not to recognize which UserForm it should act upon.
Shai Rado's advice is good and you should have a look at how he creates the object from its 'key'.
I only post this answer to check if you're aware that you could pass the object itself in the call. So your code could be like so:
Option Explicit
Public Sub RunMe()
ClearCBoxes UserForm1
End Sub
Private Sub ClearCBoxes(frm As MSForms.UserForm)
Dim ctrl As Control
For Each ctrl In frm.Controls
If TypeOf ctrl Is MSForms.ComboBox Then
ctrl.Value = False
End If
Next
End Sub
You don't need a Function (since you are not returning any arguments), in your case a Sub will do.
You need to qualify an Object to the User_Form selected by using:
Set objUserForm = UserForms.Add(userf)
Whole code
(Tested)
Option Explicit
Sub ClearUserForm(ByVal userf As String)
Dim contr As Control
Dim objUserForm As Object
Set objUserForm = UserForms.Add(userf)
For Each contr In objUserForm.Controls
If TypeName(contr) = "CheckBox" Then
contr.Value = False
End If
Next
' just to check that all checkboxes are cleared
objUserForm.Show
End Sub

VBA: how to use class module to change value of checkbox in userform

I have a userform with a lot of emailaddresses. I want the user to be able to select who to send an email to. I do so with checkboxes which are created on run time. To make it easier to use, I have also added a checkbox which allows the user to select of deselect all checkboxes.
This works perfectly as I want it to, but there is one problem I'm breaking my head over. If all checkboxes are checked and one gets unchecked, I want the "Select all" checkbox to be unchecked as well - and vice versa, if not all checkboxes were checked and the final checkbox is being checked by the user I want the "Select all" checkbox to be checked as well.
I try to do this using a class module. My overall knowledge of vba is pretty okay, but class modules are new territory for me, so excuse me if my language gets a bit fussy now.
In the initialize event of the userform I create a new collection and I assign clicks to these specific checkboxes. That works perfectly, as it doesn't give any errors in the initialize event of the userform and an event is triggered once I click one of these checkboxes. The problem I'm having is that I can't get a grip on the "Select all" checkbox (chkSelAll) in the userform. I've tried creating a public object for this checkbox in the userform (Public objSelAll As MSForms.CheckBox), but still it gives me the "Variable not defined" error once I click one of the checkboxes.
Here's the code for the class module (cls_RIRI):
Private WithEvents chkBox As MSForms.CheckBox
Public Sub AssignClicks(ctrl As Control)
Set chkBox = ctrl
End Sub
Private Sub chkBox_Click()
If chkBox.Value = False Then objSelAll.Value = False
'^This is where the error occurs: variable not defined
End Sub
And here's the relevant part of the Userform_Initialize event:
Private colTickBoxes As Collection
Public objSelAll As MSForms.CheckBox
Private Sub UserForm_Initialize()
Dim ChkBoxes As cls_RIRI
Dim ctrl As Control
Set objSelAll = Me.Controls.Item("chkSelAll")
Set colTickBoxes = New Collection
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 1) = "M" Then
Set ChkBoxes = New cls_RIRI
ChkBoxes.AssignClicks ctrl
colTickBoxes.Add ChkBoxes
End If
Next ctrl
Set ChkBoxes = Nothing
Set ctrl = Nothing
End Sub
As you can see I didn't get to the point yet where I let the code check if all checkboxes are checked so that the select all checkbox can be checked as well. I'm not really looking for this code, I'll probably manage it once I get grip on the select all checkbox from the class module, so please don't worry about this part! :)
Private WithEvents chkBox As MSForms.CheckBox
private strParentFormName as string
Public Sub AssignClicks(ctrl As Control,strFormName as string)
strParentFormName=strFormName
.....
end sub
Private Sub chkBox_Click()
dim f as userform
set f=userforms(0) <--- or loop the userforms to get form name
If chkBox.Value = False Then f.controls("objSelAll").Value = False
'^This is where the error occurs: variable not defined
End Sub
and something like this
Public Function GET_USERFORM(strUserform As String) As UserForm
Dim i As Integer
For i = 0 To UserForms.Count - 1
If UserForms(i).Name = strUserform Then
Set GET_USERFORM = UserForms(i)
Exit For
End If
Next i
End Function
You'll need to pass in the form also, as the variable doesnt exist in the class. Add a property for the formname or if you'll only have 1 form open, then use the open form or reference the form if multiples are open. Your class exists on it's own as a check box. I am not sure, but you may be able to get the parent object from the checkbox. Hope this helps.
private strFormName as string
Public Property Let ParentForm(value as string)
strFormname=value
End Property
then...
userforms(strFormname).controls("objSelectAll").value=true

VBA: Detect changes in any textbox of the userform

There is a userform that has many textboxes and I need to detect changes in each. So I have write a subroutine for every textbox in the form and it turns out a large piece of code.
As the code for every textbox is the same I want to optimize it. So is it possible to write just one subroutine that detect changes in any textbox of the form?
The only way do achieve that is to use a class along with WithEvents
Here's a minimal example:
Code for the class module named mytextbox:
Private WithEvents txtbox As MSForms.TextBox
Public Property Set TextBox(ByVal t As MSForms.TextBox)
Set txtbox = t
End Property
Private Sub txtbox_Change()
' code for handling the event
End Sub
And the code inside the Userform, assuming you want to handle the events of every Textbox
Private myEventHandlers As Collection
Private Sub UserForm_Initialize()
Dim txtbox As mytextbox
Set myEventHandlers = New Collection
Dim c As Control
For Each c In Me.Controls
If TypeName(c) = "TextBox" Then
Set txtbox = New mytextbox
Set txtbox.TextBox = c
myEventHandlers.Add txtbox
End If
Next c
End Sub

How to declare custom event in userform using vba

I have userform which collects some user input. Now what I'm trying to do, is to declare some event to throw from userform when OK button is clicked. I'm new to vba so I don't know how to do it. Any code or link to tutorial would be greatly appreciated.
Load UserForm1
UserForm1.Show
//here I want to capture UserForm1 OK button's click event and read the data
In child-form declare event and raise it at the certain moment:
Public Event clickOnChild(ByVal inputText As String)
RaiseEvent clickOnChild(Me.TextBox1.Value)
In a custom class module, worksheet class module or other user form you can catch the event. However you can't catch event in standard module because WithEvents variable are valid in object module only. To catch your event in e.g. other user form declare WithEvents variable of type childUserForm and
add event-handler where the event will be catched and handled:
Private WithEvents childForm As childUserForm
Private Sub childForm_clickOnChild(ByVal inputText As String)
Complete example:
Child user form:
Option Explicit
Public Event clickOnChild(ByVal inputText As String)
Private Sub CommandButton1_Click()
RaiseEvent clickOnChild(Me.TextBox1.Value)
End Sub
Parent user form:
Option Explicit
Private WithEvents childForm As childUserForm
Private Sub CommandButton1_Click()
childForm.Show
End Sub
Private Sub childForm_clickOnChild(ByVal inputText As String)
MsgBox "Input in child form was: " & inputText
End Sub
Private Sub UserForm_Initialize()
Set childForm = New childUserForm
End Sub
As I said in a comment, I don't think what you want to do is possible, but I thought of the following workarounds:
If your user input is very simple, like just entering a string, a messagbox could work:
Dim sUserInput As Variant
sUserInput = InputBox("Please enter something useful.", "Title", "Default")
Debug.Print "sUserInput=" & sUserInput
If you need the form to capture user input, making it modal and then exposing a value through a public method might work.
In the form:
Option Explicit
Private msFormString As String
Private Sub CommandButton1_Click()
msFormString = "Someone clicked on Button 1!"
'***** Note: if you use Unload Me, the string
'***** is unloaded with the form...
Me.Hide
End Sub
Public Function GetFormString() As String
GetFormString = msFormString
End Function
The calling code:
Load UserForm1
Call UserForm1.Show(vbModal)
Debug.Print "Value from UserForm1: " & UserForm1.GetFormString
Note: The function could return an object, class or array if you need to pass more data back.