I don't use VBA from long time....I have this form in Access 2016
When I try to access to the various TextBoxes through the Me.Controls Collection and convert it to a TextBox object, I get a Null reference but some its properties are valid (eg. tb.Name)
Private Sub Form_Load()
Dim ctrl As Control
Dim tb As TextBox
Dim evTb As clsEventTextBox
Set m_TbColl = New Collection
For Each ctrl In Me.Controls
If Left$(ctrl.Name, 4) = "Txt_" Then
Set tb = ctrl
'Create the TextBox wrapper
Set evTb = New clsEventTextBox
Set evTb.EventsHandler = Me
Set evTb.InnerTextBox = tb <----- HERE tb Is NULL
m_TbColl.Add evTb, ctrl.Name
End If
Next
End Sub
I miss something?
Also, is there a way to get the Type of a Control instead of using
Left$(ctrl.Name, 4) = "Txt_"
To get the type, use TypeName like this:
If TypeName(ctrl) = "TextBox" Then
And to ensure tb takes the form of a Textbox object, use this
Set tb = Controls(ctrl.Name)
You haven't shown the class that you're using, but assuming it looks something like this:
Private WithEvents f_EH As Access.Form
Private WithEvents f_TB As Access.TextBox
Public Property Set EventsHandler(frm As Access.Form)
Set f_EH = frm
End Property
Public Property Set InnerTextBox(ctl As Access.TextBox)
Set f_TB = ctl
End Property
If I use a class with that structure, the code in your post works fine. But notice that I've explicitly set the expected type of the InnerTextBox property to Access.TextBox.
But your code does needless casting, uses Hungarian naming (yuck!), and relies on the first 4 characters of the name being "Txt_" and could be written as:
Dim ctrl As Control
Dim evTb As clsEventTextBox
Set m_TbColl = New Collection
For Each ctrl In Me.Controls
If TypeOf ctrl Is Access.TextBox Then
'Create the TextBox wrapper
Set evTb = New clsEventTextBox
Set evTb.EventsHandler = Me
Set evTb.InnerTextBox = ctrl 'Just pass the ctrl reference without casting
m_TbColl.Add evTb, ctrl.Name
End If
Next
Note the use of TypeOf in If TypeOf ctrl Is Access.TextBox Then to determine whether the control is a TextBox.
Related
I am working on a project where I have to use MS Access and I have to make the database as loose as possible (Its weird and I dont think best practice but for now given my resources it is what I have).
Anyways I have 50 combo boxes but often have to make changes to one which would mean I have to manually change all of them. Id rather spend hour finding a programming solution then 5 minutes manually doing this.
I need to change the 'OnChange' event using VBA but my code produces an error.
Private Function RunChangePropagate()
Dim combo As ComboBox
RevealGrid
For Each combo In Me.Controls
combo.OnChange = "=ComboBox_Change()"
Next combo
ClearGrid
End Function
Error:
I have also tried making the text to change it to a Variant and then assigning the event to said Variant.
How do I go about doing this?
Thanks in advance.
This is some minimal example, that works:
Public Sub ChangeEvent()
Dim ctrl As Control
For Each ctrl In Me.Controls
If ctrl.Name = "Combo5" Then
Debug.Print ctrl.OnChange
ctrl.OnChange = "SomeProcedure"
End If
Next ctrl
End Sub
In your example you should only remove the = in the assigning. The parenthesis at the end of the assigned sub are not required.
Use WithEvents. This way, you form is completely "detached" from the class controlling (some controls of) the form.
I published an article with links and an example for anyone to study:
Create Windows Phone Colour Palette and Selector using WithEvents
The main code (code behind module and class module) is only:
Option Explicit
' Helper class for form Palette for event handling of textboxes.
' 2017-04-19. Gustav Brock, Cactus Data ApS, CPH.
' Version 1.0.0
' License: MIT.
' *
Private Const EventProcedure As String = "[Event Procedure]"
Private WithEvents ClassTextBox As Access.TextBox
Public Sub Initialize(ByRef TextBox As Access.TextBox)
Set ClassTextBox = TextBox
ClassTextBox.OnClick = EventProcedure
End Sub
Public Sub Terminate()
Set ClassTextBox = Nothing
End Sub
Private Sub ClassTextBox_Click()
' Select full content.
ClassTextBox.SelStart = 0
ClassTextBox.SelLength = Len(ClassTextBox.Value)
' Display the clicked value.
ClassTextBox.Parent!CopyClicked.Value = ClassTextBox.Value
' Copy the clicked value to the clipboard.
DoCmd.RunCommand acCmdCopy
End Sub
and:
Option Explicit
' Form to display the Windows Phone 7.5/8.0 colour theme.
' Also works as a basic example of implementing WithEvents for a form.
' 2017-04-19. Gustav Brock, Cactus Data ApS, CPH.
' Version 1.0.0
' License: MIT.
' *
Private ControlCollection As Collection
Private Sub Form_Load()
' Load events for all colour value textboxes.
Dim EventProcedure As ClassTextboxSelect
Dim Control As Access.Control
Set ControlCollection = New Collection
For Each Control In Me.Controls
If Control.ControlType = acTextBox Then
Set EventProcedure = New ClassTextboxSelect
EventProcedure.Initialize Control
ControlCollection.Add EventProcedure, Control.Name
End If
Next
Set EventProcedure = Nothing
Set Control = Nothing
End Sub
Private Sub Form_Unload(Cancel As Integer)
' Unload events for all colour value textboxes.
Dim EventProcedure As ClassTextboxSelect
For Each EventProcedure In ControlCollection
EventProcedure.Terminate
Next
Set EventProcedure = Nothing
Set ControlCollection = Nothing
End Sub
Full code is also on GitHub: VBA.ModernTheme
I have been working on a project and have multiple tick boxes (25) and multiple labels in a form that are names SC1, SC2...SCN and Lbl1, Lbl2...LblN depending on a recordset. When I click the tickbox I want the label beside it to display some information, see below -
Private Sub SC1_Click()
If (Me!SC1) = True Then
Form.Controls("Lbl1").Caption = ("Completed by " & (Environ$("Username")))
Form.Controls("Lbl1").ForeColor = vbGreen
Else
Form.Controls("Lbl1").Caption = ("Please tick if Complete")
Form.Controls("Lbl1").ForeColor = vbBlack
End If
End Sub
My issue is I can't change the number in the Sub name so I would have to create multiple sub procedures. I think if I created a class for the tick box this would change but I am not sure how I can set up the class. I have tried the below class template but am not sure where I can change the property values in order to reach my goal. I am not sure why you would have both get and set properties in one class. Any help on this is greatly appreciated.
Option Compare Database
Option Explicit
Private pName As String
Private pCaption As String
Private pVisiblity As Boolean
Private pValue As Boolean
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property
Public Property Get Caption() As String
Caption = pCaption
End Property
Public Property Let Caption(Value As String)
pCaption = "Please Tick Box if complete"
End Property
Public Property Get Visibility() As Boolean
Visibility = pVisibility
End Property
Public Property Let Visibility(Value As Boolean)
pVisibility = True
End Property
Public Property Get Value() As Boolean
Value = pValue
End Property
Public Property Let Value(Value As Boolean)
pValue = True
End Property
There are two parts to creating and linking form controls to custom support objects (classes). In your case
Class Module: clsMyCheckbox
Option Explicit
Option Compare Database
Public WithEvents chkBox As CheckBox
Public chkLabel As Label
Private currentUser As String
Private Sub chkBox_Click()
If chkBox.Value = True Then
chkLabel.Caption = "Completed by " & currentUser
chkLabel.ForeColor = vbGreen
Else
chkLabel.Caption = "Please tick if Complete"
chkLabel.ForeColor = vbBlack
End If
End Sub
Private Sub Class_Initialize()
currentUser = Environ$("Username")
End Sub
And in your form module:
Option Explicit
Option Compare Database
Private localCheckboxes As New Collection
Private Sub Form_Load()
'--- find all the checkboxes on the form and create a
' handler object for each one
Dim ctl As Control
Dim chknum As String
Dim cbObj As clsMyCheckbox
Dim chkLbl As Label
For Each ctl In Me.Controls
If ctl.ControlType = acCheckBox Then
'--- you can filter by name if needed
If ctl.Name Like "SC*" Then
chknum = Right(ctl.Name, Len(ctl.Name) - 2)
Set chkLbl = Me.Controls.Item("Lbl" & chknum)
chkLbl.Caption = "initialized" 'optional during form load
Set cbObj = New clsMyCheckbox 'class object for this checkbox
Set cbObj.chkBox = ctl 'link the control to the object
Set cbObj.chkLabel = chkLbl 'link the label too
'--- add it to a local store so the object persists
' as long as the form is open
localCheckboxes.Add cbObj
End If
End If
Next ctl
End Sub
Private Sub Form_Unload(Cancel As Integer)
'--- guarantee the objects are destroyed with the form
Set localCheckboxes = Nothing
End Sub
I think you are going the wrong way. In Access you can't really derive your own classes for GUI control and use them on the form. For your problem, you basically have three options:
Use the default event handlers and call one custom function from each. This will improve your situation a little.
Use one custom event handler for all checkboxes, instead of the default event-handlers.
Use a class and attach an instance to each of the checkboxes you use. The class can then recieve any event from the checkbox. This is powerful but you will still need to register your class with each control and hold all you instances somewhere for this to work.
For your problem, I'd go with solution 2:
First, write a custom event handler like this in your Form-module:
Private Function chkClick(sName As String)
Debug.Print "Clicked: " & sName
Me.Controls(sName).Controls(0).Caption = "x"
End Function
Next, enter design mode of you form and go to all checkboxes. In Checkbox "SC1", you go to the "OnClick" event and enter =chkClick("SC1") as event handler instead of [Eventprocedure]. Make sure you use the correct name of the control as the parameter of the function.
Congratulations! From now on, all your checkboxes will call the same event-handler and pass their name. Since the label of a checkbox is its associated control, you get to that label from the checkbox via .Controls(0), meaning the first "sub"-control of the checkbox. This way, you don't need to know the name of the associated label at all!
I would like to know how can I export data from VB6 textbox to a HTML textbox? It could be a simple html page or an asp page.
for example, on my VB6 form, i have an name field. Upon clicking of a button on the VB6 form, the data in the name field will be exported to a textbox on the html page.
Thank you all for help and time for reading this.
To see this demo in action, and be able to follow it through and learn how to grab from it what you need:
Create a form with a lable over a textbox, and stick 1 command buttons on the form. Don't rename any of them - the program expects the text1, command1
The following CODE is the complete FORM CODE to copy/paste into it.
Add refernce to your project from (Project=>References)Microsoft Internet Controls,Microsoft HTML Object Library,
Option Explicit
Public TargetIE As SHDocVw.InternetExplorer
Private Sub Command1_Click() ' Send text to first IE-document found
GetTheIEObjectFromSystem
SendTextToActiveElementWithSubmitOptionSet (False)
End Sub
Private Sub Form_Load()
Me.Text1 = "This is a sample text message set and submitted programmatically" 'make text1 multiline in design
Me.Command1.Caption = "Text to the first IE browser document found"
End Sub
Public Sub GetTheIEObjectFromSystem(Optional ByVal inurl As String = ".") ' "." will be found in ALL browser URLs
Dim SWs As New SHDocVw.ShellWindows
Dim IE As SHDocVw.InternetExplorer
Dim Doc As Object
For Each IE In SWs
If TypeOf IE.Document Is HTMLDocument Then ' necessary to avoid Windows Explorer
If InStr(IE.LocationURL, inurl) > 0 Then
Set TargetIE = IE
Exit For
End If
End If
Next
Set SWs = Nothing
Set IE = Nothing
End Sub
Private Sub SendTextToActiveElementWithSubmitOptionSet(ByVal bSubmitIt As Boolean)
Dim TheActiveElement As IHTMLElement
Set TheActiveElement = TargetIE.Document.activeElement
If Not TheActiveElement.isTextEdit Then
MsgBox "Active element is not a text-input system"
Else
TheActiveElement.Value = Me.Text1.Text
Dim directParent As IHTMLElement
If bSubmitIt Then
Dim pageForm As IHTMLFormElement
Set directParent = TheActiveElement.parentElement
' find its parent FORM element by checking parent nodes up and up and up until found or BODY
Do While (UCase(directParent.tagName) <> "FORM" And UCase(directParent.tagName <> "BODY"))
Set directParent = directParent.parentElement
Loop
If UCase(directParent.tagName) = "FORM" Then
Set pageForm = directParent
pageForm.submit 'intrinsic Form-element Method
Else
MsgBox ("Error: No form unit for submitting the text on this page!")
End If
End If
Set pageForm = Nothing
Set directParent = Nothing
End If
Set TheActiveElement = Nothing
Set TargetIE = Nothing
End Sub
I have an Access 2007 app that I'm updating to be able to run on both 2007 and 2010. In 2007 I use the form ribbon property, but with 2010 I've needed to make a default ribbon that turns off the backstage. I've done that but the app needs too set it as default when it detects that it is running on 2010 instead of 2007. The Load custom UI does not work. It loads it but it does not set a ribbon as default. I know I can set the default start up form and other properties with the database.properties function. But I need to know the property name for the application default ribbon. Anyone know the property names?
I think the name of the Database Property your looking for is: CustomRibbonId
Here's some code to output a list of Database Properties to the Debug window.
Private Sub EnumerateDatabaseProperties()
On Error Resume Next
Dim p1 As DAO.Property, s1 As String
For Each p1 In CurrentDb.Properties
s1 = p1.Name
s1 = s1 & "=" & p1.value
Debug.Print s1
Next p1
End Sub
Do realize that a database property might not show up in the output if it doesn't exist, rather than just showing up in the output with no value.
First we need a robust method for setting DB properties.
Public Sub SetCurrentDBProperty(ByVal propertyName As String, ByVal newValue As Variant, Optional ByVal prpType As Long = dbText)
Dim thisDBs As Database
Set thisDBs = CurrentDb
Dim wasFound As Boolean
' Look for property in collection
Dim thisProperty As Object ' DAO.Property
For Each thisProperty In thisDBs.Properties
If thisProperty.Name = propertyName Then
' Check for matching type
If thisProperty.Type <> prpType Then
' Remove so we can add it back in with the correct type.
thisDBs.Properties.Delete propertyName
Exit For
End If
wasFound = True
' Skip when no change is required
If thisProperty.Value = newValue Then
Exit For
Else
' Update value
thisProperty.Value = newValue
End If
End If
Next thisProperty
If Not wasFound Then
' Add new property
Set thisProperty = thisDBs.CreateProperty(propertyName, prpType, newValue)
thisDBs.Properties.Append thisProperty
End If
End Sub
Then given an example ribbon name of Runtime you could call the property setter like this:
Public Sub SetRuntimeRibbon()
SetCurrentDBProperty "CustomRibbonID", "Runtime"
End Sub
Code to create new form instance of a closed form using form name
I want to replace the long Select Case list with a variable.
Full code of module
In Access 2010 I have a VBA function that opens a new instance of a form when given a string containing the form's name. By adding a form variable "frm" to a collection:
mcolFormInstances.Add Item:=frm, Key:=CStr(frm.Hwnd)
The only way I can figure out to open "frm" is with a Select Case statement that I've manually entered.
Select Case strFormName
Case "frmCustomer"
Set frm = New Form_frmCustomer
Case "frmProduct"
Set frm = New Form_frmProduct
... etc ... !
End Select
I want it to do it automatically, somewhat like this (although this doesn't work):
Set frm = New Eval("Form_" & strFormName)
Or through some code:
For Each obj In CurrentProject.AllForms 'or AllModules, neither work
If obj.Name = strFormName Then
Set FormObject = obj.AccessClassObject 'or something
End If
Next
Set frm = New FormObject
I just want to avoid listing out every single form in my project and having to keep the list updated as new forms are added.
I've also done some testing of my own and some reading online about this. As near as I can tell, it isn't possible to create a new form object and set it to an instance of an existing form using a string that represents the name of that form without using DoCmd.OpenForm.
In other words, unless someone else can prove me wrong, what you are trying to do cannot be done.
I think you are looking for something like this MS-Access 2010 function. (The GetForm sub is just for testing):
Function SelectForm(ByVal FormName As String, ByRef FormExists As Boolean) As Form
For Each f In Application.Forms
If f.Name = FormName Then
Set SelectForm = f
FormExists = True
Exit Function
End If
Next
FormExists = False
End Function
Sub GetForm(ByVal FormName As String)
Dim f As New Form
Dim FormExists As Boolean
Set f = SelectForm(FormName, FormExists)
If FormExists Then
MsgBox ("Form Found: " & f.Caption)
Else
MsgBox ("Form '" & FormName & "' not found.")
End If
End Sub
Here's an ugly hack I found:
DoCmd.SelectObject <acObjectType>, <YourObjectsName>, True
DoCmd.RunCommand acCmdNewObjectForm
The RunCommand step doesn't give you programmatic control of the object, you'll have to Dim a Form variable and Set using Forms.Item(). I usually close the form after DoCmd.RunCommand, then DoCmd.Rename with something useful (my users don't like Form1, Form2, etc.).
Hope that helps.