I have a UserForm with a MultipageControl (name Controller_MultiPage).
At runtime my code adds pages to the Multipage and creates a newListView on each page.
Every ListView has:
With newListView
.MultiSelect = False
.Width = Controller_MultiPage.Width - 10
.Height = Controller_MultiPage.Height - 20
.View = lvwReport
.HideColumnHeaders = False
.ColumnHeaders.Add Text:="Signal Name", Width:=.Width / 10 * 4
.ColumnHeaders.Add Text:="Type", Width:=.Width / 10
.ColumnHeaders.Add Text:="I/O", Width:=.Width / 10
.ColumnHeaders.Add Text:="Description", Width:=.Width / 10 * 4
.CheckBoxes = True
.FullRowSelect = True
End With
then I populate the newListView with data from an XML file:
For Each node In list
With node.Attributes
Set listItem = newListView.ListItems.Add(Text:=.getNamedItem("Name").Text)
listItem.ListSubItems.Add = .getNamedItem("Type").Text
listItem.ListSubItems.Add = IIf(.getNamedItem("Input").Text = "1", "IN", "OUT")
listItem.ListSubItems.Add = .getNamedItem("Description").Text
listItem.Checked = False
End With
Next
but the checkboxes do not show. I can see the space for them in front of the first column and by clicking that space the checkbox of that particular row then appears. What I also noticed is that if I change the property
listItem.Checked = True
the behavior described above does not change, and when I click the free space in front of the first column (checkboxes space) the chsckbox that then shows up is still unchecked.
Any idea?
The problem seems to be in the behavior of the MultiPage control.
What I noticed was that if I forced the checkboxes' status (checked or unchecked) from the code, using the MultiPage_Change event, then the checkboxes show up.
So what I did was to create a class that holds the status of all checkboxes of all listviews on a single page, instantiate the Class for each ListView and store everything into a Dictionary, using the newListView.Name as Key
Then when the user changes page, the MultiPage_Change event that fires resets all the values of the checkboxes according to the Dictionary stored values.
In the Listview_N_ItemChecked event some other code updates the status of the item stored in the Dictionary.
Kind of cumbersome but it works.
the class (updated):
' Class Name = ComponentsSignalsRecord
Option Explicit
Dim Name As String
' NOTE: Signals(0) will always be empty and status(0) will always be False
Dim Signals() As String
Dim Status() As Boolean
Dim Component As String
Property Let SetComponentName(argName As String)
Component = argName
End Property
Property Get GetComponentName() As String
GetComponentName = Component
End Property
Property Get getSignalName(argIndex) As String
If argIndex >= LBound(Signals) And argIndex <= UBound(Signals) Then
getSignalName = Signals(argIndex)
Else
getSignalName = vbNullString
End If
End Property
Property Get dumpAll() As String()
dumpAll = Signals
End Property
Property Get Count() As Long
Count = UBound(Signals)
End Property
Property Get getStatus(argName As String) As Integer
' returns: -1 = Not Found; 1 = True; 0 = False
getStatus = -1
Dim i As Integer
For i = 0 To UBound(Signals)
If argName = Signals(i) Then getStatus = IIf(Status(i) = True, 1, 0): Exit For
Next
End Property
Property Let setName(argName As String)
Name = argName
End Property
Property Get getName() As String
getName = Name
End Property
Public Sub UncheckAll()
Dim i As Integer
For i = 0 To UBound(Status)
Status(i) = False
Next
End Sub
Public Sub CheckAll()
Dim i As Integer
For i = 0 To UBound(Status)
Status(i) = True
Next
End Sub
Public Sub deleteSignal(argName As String)
Dim spoolSignals() As String
Dim spoolStatus() As Boolean
Dim i As Integer
spoolSignals = Signals
spoolStatus = Status
ReDim Signals(0)
ReDim Status(0)
For i = 1 To UBound(spoolSignals)
If argName <> spoolSignals(i) Then
ReDim Preserve Signals(UBound(Signals) + 1): Signals(UBound(Signals)) = spoolSignals(i)
ReDim Preserve Status(UBound(Status) + 1): Status(UBound(Status)) = spoolStatus(i)
End If
Next
End Sub
Public Sub addSignal(argName As String, argValue As Boolean)
Dim i As Integer
For i = 0 To UBound(Signals)
If argName = Signals(i) Then GoTo bye
Next
ReDim Preserve Signals(UBound(Signals) + 1)
ReDim Preserve Status(UBound(Status) + 1)
Signals(UBound(Signals)) = argName
Status(UBound(Status)) = argValue
bye:
End Sub
Public Sub setStatus(argName As String, argValue As Boolean)
Dim i As Integer
For i = 0 To UBound(Signals)
If argName = Signals(i) Then Status(i) = argValue: Exit For
Next
End Sub
Private Sub Class_Initialize()
ReDim Signals(0)
ReDim Status(0)
End Sub
The Form relevant code. Module level:
Dim myDict As New Dictionary ' the Dictionary
Dim ComponentsSignalsList As ComponentsSignalsRecord ' the Class
for each ListView created, may be one or more for every single MultiPage page :
Set ComponentsSignalsList = New ComponentsSignalsRecord
ComponentsSignalsList.setName = newListView.name
while populating the listview(s) in a loop for each single item added:
ComponentsSignalsList.addSignal List_Item.Text, List_Item.Checked
end of each loop, add the Class instance to the Dictionary:
myDict.Add ComponentsSignalsList.getName, ComponentsSignalsList
Now when changing Page in the MultiPage widget:
Private Sub Controller_MultiPage_Change()
If isLoading Then Exit Sub 'avoid errors and undue behavior while initializing the MultiPage widget
Dim locControl As Control
Dim controlType As String: controlType = "ListView"
With Controller_MultiPage
For Each locControl In .Pages(.value).Controls
If InStr(1, TypeName(locControl), controlType) > 0 Then
Call Check_CheckBoxes(locControl)
End If
Next
End With
End Sub
Private Sub Check_CheckBoxes(argListView As listView)
If argListView.CheckBoxes = False Then Exit Sub 'some ListViews don't have checkboxes
Dim myItem As ListItem
For Each myItem In argListView.ListItems
With myItem
.Checked = myDict.Item(argListView.name).getStatus(.Text)
End With
Next
End Sub
when ticking/unticking a checkbox (note the the ItemChecked event handler is defined in another Class Public WithEvents, where the handler calls this method passing both the ListView ID and the Item object) :
Public Sub ListViewsEvents_ItemCheck(argListView As listView, argItem As MSComctlLib.ListItem)
With argItem
myDict.Item((argListView .name).setStatus argName:=.Text, argValue:=.Checked
End With
End Sub
I just found the answer to the same problem that I also had and I feel so stupid. I had the first column of the Listview set to Width = 0... and thus the checkboxes would no longer show.
I gave it a width and everithing is back to normal...
Related
I have a UserForm with Text and Combo Boxes, some of which represent "REQUIRED FIELDS" and cannot be left blank. I have entered the value RQD for the tag property of the target controls. My objective is to loop through the controls and use their Tag property to identify controls that cannot be empty (where Tag property value = RQD) and change their BackColor property if they are. However, I cannot get this work. Below is some of the code:-
With frm_RecCapture
'
.lbl01_RecDate = Format(Date, "Long Date", vbSunday)
.txt01_RecNum = Format(RecNum, "000000")
.txt01_RecNum.Enabled = False
.txt01_AccNum.SetFocus
'
frmComplete = False
.Show
'
Do While frmComplete = False
.Show
'
For Each frmCtrl In .Controls
If TypeName(frmCtrl) = "Textbox" Or TypeName(frmCtrl) = "Combobox" Then
If frmCtrl.Tag = "RQD" And frmCtrl.Text = "" Then
frmCtrl.BackColor = &HFFFF&
n = n + 1
End If
End If
Next frmCtrl
'
If n = 0 Then
frmComplete = True
Else
frmComplete = False
MsgBox "ERROR! Fields highlighted in yellow cannot be left blank. Please "
complete these fields before continuing.", vbInformation + vbOKOnly, SysTitle
End If
Loop
'
End With
Any suggestions? Thanks...
I prefer writing a class that wraps and validates a control. You will need to store a reference to the wrapper class in a collection of some type of class level variable keep it from falling out of scope.
Class: RequiredFieldControl
Option Explicit
Private WithEvents ComboBox As MSForms.ComboBox
Private WithEvents TextBox As MSForms.TextBox
Private mControl As MSForms.Control
Private Const DefaultBackColor As Long = -2147483643
Private Const InvalidBackColor As Long = vbYellow ' &HFFFF&
Public Property Set Control(ByVal Value As MSForms.Control)
Set mControl = Value
Select Case TypeName(Control)
Case "ComboBox"
Set ComboBox = Value
Case "TextBox"
Set TextBox = Value
End Select
FormatControl
End Property
Public Property Get Control() As MSForms.Control
Set Control = mControl
End Property
Sub FormatControl()
Control.BackColor = IIf(isValid, DefaultBackColor, InvalidBackColor)
End Sub
Public Function isValid() As Boolean
Select Case TypeName(Control)
Case "ComboBox"
isValid = ComboBox.ListIndex > -1
Case "TextBox"
isValid = Len(TextBox.Value) > 0
End Select
End Function
Private Sub ComboBox_Change()
FormatControl
End Sub
Private Sub TextBox_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
FormatControl
End Sub
Form Code
Private RequiredFields As Collection
Private Sub UserForm_Initialize()
Set RequiredFields = New Collection
AddRequiredFields Me.Controls
ComboBox1.List = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Debug.Print RequiredFields.Count
End Sub
Sub AddRequiredFields(pControls As MSForms.Controls)
Dim RequiredField As RequiredFieldControl
Dim Control As MSForms.Control
For Each Control In pControls
If Control.Tag = "RQD" Then
Select Case TypeName(Control)
Case "ComboBox", "TextBox"
Set RequiredField = New RequiredFieldControl
Set RequiredField.Control = Control
RequiredFields.Add RequiredField
End Select
Else
On Error Resume Next
AddRequiredFields Control.Controls
On Error GoTo 0
End If
Next
End Sub
Function AreAllRequiredFieldsFilled() As Boolean
Dim RequiredField As RequiredFieldControl
For Each RequiredField In RequiredFields
If Not RequiredField.isValid Then Exit Function
Next
AreAllRequiredFieldsFilled = True
End Function
I've created a code in VBA to collect data using a multi-page control. In each page, I've added checkboxes dynamically based on rows from the worksheet in Excel and, for each checkbox, there's a textbox and 2 command buttons, just like the image below:
Input Window:
The code to automatically add controls is:
Private Sub UserForm_Initialize()
fmat_disp.Value = 0
fmat_set.Value = 0
'---------------------------------------------------------------------------------------------
'Inspeção de Mecânica
Sheets("Mecânica").Activate
n_anom = Application.WorksheetFunction.CountA(Range("1:1")) - 1
AreasInspecao.mecanica.ScrollHeight = 10 + 18 * (n_anom)
For i = 1 To n_anom
'Selecionar anomalia
Set SelAnom = AreasInspecao.mecanica.Controls.Add("Forms.CheckBox.1", "sel_anom_" & i)
SelAnom.Caption = Worksheets("Mecânica").Cells(1, i + 1)
SelAnom.AutoSize = True
SelAnom.Height = 18
SelAnom.Left = 5
SelAnom.Top = 5 + (SelAnom.Height) * (i - 1)
SelAnom.Tag = i
Same goes to the textbox and plus/minus buttons, only changing the captions.
What I want is:
1) when CHECKBOX is CHECKED, respective TEXTBOX must show 1
2) when MINUS sign is PRESSED, respective TEXTBOX must decrement
3) when PLUS sign is PRESSED, respective TEXTBOX must increment
4) when "Finalizar Inspeção" is PRESSED, all data collected must be sent to Excel, filling a worksheet.
I simply don't know how to link each button/checkbox to your respective textbox without creating a subroutine for each one! I'll have ~500 subroutines....that's impossible to manage manually....
OK here's a rough outline for handling the click events on the checkboxes and buttons.
First two custom classes for capturing the clicks: each of these is very simple - all they do is call a method on the userform with the clicked control as an argument.
'clsCheck
Public WithEvents chk As MSForms.CheckBox
Private Sub chk_Click()
frmExample.HandleClick chk
End Sub
'clsButton
Public WithEvents btn As MSForms.CommandButton
Private Sub btn_Click()
frmExample.HandleClick btn
End Sub
Userform code - my form is named "frmExample".
Note the naming convention which allows groups of controls to be treated as a "unit".
Option Explicit
'These two global collections hold instances of the custom classes
Dim colCheckBoxes As Collection
Dim colButtons As Collection
Private Sub UserForm_Activate()
Const CON_HT As Long = 18
Dim x As Long, cbx As MSForms.CheckBox, t
Dim btn As MSForms.CommandButton, txt As MSForms.TextBox
Dim oCheck As clsCheck, oButton As clsButton
Set colCheckBoxes = New Collection
Set colButtons = New Collection
For x = 1 To 10
t = 5 + CON_HT * (x - 1)
Set cbx = Me.Controls.Add("Forms.CheckBox.1", "cbox_" & x)
cbx.Caption = "Checkbox" & x
cbx.Width = 80
cbx.Height = CON_HT
cbx.Left = 5
cbx.Top = t
colCheckBoxes.Add GetCheckHandler(cbx) '<< save in collection
Set btn = Me.Controls.Add("Forms.CommandButton.1", "btnplus_" & x)
btn.Caption = "+"
btn.Height = CON_HT
btn.Width = 20
btn.Left = 90
btn.Top = t
btn.Enabled = False '<<buttons start off disabled
colButtons.Add GetButtonHandler(btn) '<< save in collection
Set btn = Me.Controls.Add("Forms.CommandButton.1", "btnminus_" & x)
btn.Caption = "-"
btn.Height = CON_HT
btn.Width = 20
btn.Left = 130
btn.Top = t
btn.Enabled = False '<<buttons start off disabled
colButtons.Add GetButtonHandler(btn) '<< save in collection
'no events are captured for the textboxes...
Set txt = Me.Controls.Add("Forms.Textbox.1", "txt_" & x)
txt.Width = 30
txt.Height = CON_HT
txt.Left = 170
txt.Top = t
Next x
End Sub
'All "clicked" controls saved in instances of the custom classes
' get passed here. Handle based on control type/name
Public Sub HandleClick(ctrl As MSForms.Control)
Dim num
num = Split(ctrl.Name, "_")(1) 'which set of controls are we working with?
Dim txt As MSForms.TextBox
'get the matching text box...
Set txt = Me.Controls("txt_" & num)
If ctrl.Name Like "cbox_*" Then
If ctrl.Value Then txt.Value = 1
Me.Controls("btnplus_" & num).Enabled = ctrl.Value
Me.Controls("btnminus_" & num).Enabled = ctrl.Value
ElseIf ctrl.Name Like "btnplus_*" Then
txt.Value = txt.Value + 1
ElseIf ctrl.Name Like "btnminus_*" Then
txt.Value = txt.Value - 1
End If
End Sub
'couple of "factory" functions for the event-handling classes
Private Function GetCheckHandler(cb As MSForms.CheckBox)
Dim rv As New clsCheck
Set rv.chk = cb
Set GetCheckHandler = rv
End Function
Private Function GetButtonHandler(btn As MSForms.CommandButton)
Dim rv As New clsButton
Set rv.btn = btn
Set GetButtonHandler = rv
End Function
Sample file: https://www.dropbox.com/s/k74c08m0zkwn9l7/tmpFormEvents.xlsm?dl=0
Background:
I needed a function to correlate Controls efficiently based on a STD name and the text analyzed. IG:
a) Some other input throws the variable "mytext"
b) If the ListBox1.Value has "mytext" then I have to relate it with ToggleButton1
Approach:
I made the following function which partially works
Code:
Private Function RelateControl_ToggleVsList(ToggleCtrl As Control) As Control
Dim ItemControl As Control
Dim myControl As Object
For Each ItemControl In Me.Controls
If TypeName(ItemControl) = "ListBox" Then ' 1. If TypeName(ItemControl) = "Label"
'text lenghts const 13 for ListBox_TimeXX and 22 for ToggleButton_PriorityXX
If Mid(ItemControl.Name, 13, 2) = Mid(ToggleCtrl.Name, 22, 2) Then Set RelateControl_ToggleVsList = ItemControl: Exit Function
End If ' 1. If TypeName(ItemControl) = "Label"
Next ItemControl
End Function
Problem:
I get a null property when Setting the result:
Set RelateControl_ToggleVsList = ItemControl 'This is nullSet
Debugging process:
Question:
How can I set a Control as a result of this function?
EDIT:
Per request I add the whole Debugging in order to see where it is being called form
Calling Code
Private Sub ToggleButtons_Active()
Dim ItemControl As Control
Dim ItemTextBox As Variant
Dim TxtControl As String
For Each ItemControl In Me.Controls
If TypeName(ItemControl) = "ToggleButton" Then ' 1. If TypeName(ItemControl) = "ToggleButton"
TxtControl = CStr(RelateControl_ToggleVsList(ItemControl).Value)
If InStr(TextBox_Notes.Value, TxtControl) > 0 And TxtControl <> "" Then ItemControl.Value = True
End If ' 1. If TypeName(ItemControl) = "ToggleButton"
Next ItemControl
End Sub
Your error is occurring on your line which says
TxtControl = CStr(RelateControl_ToggleVsList(ItemControl).Value)
because the returned Control's Value property is currently Null which can't be cast to a String.
I recommend that you change TxtControl to be a Variant type, then say
TxtControl = RelateControl_ToggleVsList(ItemControl).Value
If IsNull(TxtControl) Then
TxtControl = ""
Else
TxtControl = CStr(TxtControl)
End If
Or you could define a Control object and then use it:
Dim MyControl As Control
MyControl = RelateControl_ToggleVsList(ItemControl)
If IsNull(MyControl.Value) Then
TxtControl = ""
Else
TxtControl = CStr(MyControl.Value)
End If
Solution:
The object itself is calling a property which does not belong to it (as intended).
ListBox Properties does not show "Value" as its text, the real thing should have called it as:
TxtControl = CStr(RelateControl_ToggleVsList(ItemControl).List(0))CStr(RelateControl_ToggleVsList(ItemControl).List(0))
Furthermore:
Thanks to the solutions provided and the debugging process, I could notice even the object is Set in the function, it is shown as the "value" property of it while debugging.
I have a list of checkboxes and after some of them are checked I would like to know which ones are checked so I can work with those checked boxes. Not sure why these few lines don't work. After I execute it there is a pop up error message saying "Object required" Run-time error '424': and highlights line => ReDim SelectedItemArray(ListBox1.ListCount) As String. Yes I have four ListBoxes; ListBox1, ListBox2, ListBox3, ListBox4. Any help is appreciated. Thank you
Sub CheckedBoxes()
Dim SelectedItemArray() As String
ReDim SelectedItemArray(ListBox1.ListCount) As String
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then
SelectedItemArray(i) = ListBox1.List(i)
End If
Next
End Sub
You need to fully qualifying the listbox. For example Sheet1.ListBox1.ListCount
This is a function I use for ListBoxes on a UserForm. I modified it (further below) for use on Worksheet listboxes.
For form controls ListBox on a UserForm, call it like:
myArray = GetSelectedItems(ListBox1)
Here's the function which will accept any listbox from a UserForm as a named argument:
Public Function GetSelectedItems(lBox As MSForms.ListBox) As Variant
'returns an array of selected items in a ListBox
Dim tmpArray() As Variant
Dim i As Integer
Dim selCount As Integer
selCount = -1
For i = 0 To lBox.ListCount - 1
If lBox.Selected(i) = True Then
selCount = selCount + 1
ReDim Preserve tmpArray(selCount)
tmpArray(selCount) = lBox.List(i)
End If
Next
If selCount = -1 Then
GetSelectedItems = Array()
Else:
GetSelectedItems = tmpArray
End If
End Function
If you are referring to a ListBox on a worksheet, try this instead:
Call it like this:
myArray = GetSelectedItems(Sheet1.Shapes("List Box 1").OLEFormat.Object)
Here's the function modified for Worksheet form control ListBox:
Public Function GetSelectedItems(lBox As Object) As Variant
'returns an array of selected items in a ListBox
Dim tmpArray() As Variant
Dim i As Integer
Dim selCount As Integer
selCount = -1
For i = 1 To lBox.ListCount - 1
If lBox.Selected(i) = True Then
selCount = selCount + 1
ReDim Preserve tmpArray(selCount)
tmpArray(selCount) = lBox.List(i)
End If
Next
If selCount = -1 Then
GetSelectedItems = Array()
Else:
GetSelectedItems = tmpArray
End If
End Function
I have created a form where I am dynamically creating Textboxes and corresponding Comboboxes along with Combobox change event. Here is the class creating combobox event handler
Option Explicit
Public WithEvents cbx As MSforms.Combobox
Private avarSplit As Variant
Sub SetCombobox(ctl As MSforms.Combobox)
Set cbx = ctl
End Sub
Private Sub cbx_Change()
Dim i As Integer
If cbx.ListIndex > -1 Then
'MsgBox "You clicked on " & cbx.Name & vbLf & "The value is " & cbx.Value
avarSplit = Split(cbx.Name, "_")
'DecessionOnValue
End If
End Sub
And here is the code on the form which is dynamically creating textboxes and Comboboxes
Function AddTextBox(Frame1 As frame, numberOfColumns As Integer)
Dim counter As Integer
Dim i As Integer
Dim TxtBox As MSforms.TextBox
For counter = 1 To numberOfColumns
'Forms.CommandButton.1
Set TxtBox = Frame1.Controls.Add("Forms.TextBox.1")
TxtBox.Name = "tb_" + CStr(counter)
'Bouton.Caption = "Test"
TxtBox.Visible = True
i = Property.TextBoxDisable(TxtBox)
' Defining coordinates TextBox height is 18
If counter = 1 Then
TxtBox.Top = 23
Else
TxtBox.Top = (18 * counter) + 5 * counter
End If
TxtBox.Left = 50
Next counter
End Function
Function Combobox(Frame1 As frame, numberOfColumns As Integer)
Dim counter As Integer
Dim i As Integer
Dim CbBox As MSforms.Combobox
Dim cbx As ComboWithEvent
If pComboboxes Is Nothing Then Set pComboboxes = New Collection
For counter = 1 To numberOfColumns
'Forms.CommandButton.1
Set CbBox = Frame1.Controls.Add("Forms.ComboBox.1")
CbBox.Name = "cb_" + CStr(counter)
i = AddComboboxValues(CbBox)
' Defining coordinates TextBox height is 18
If counter = 1 Then
CbBox.Top = 23
Else
CbBox.Top = (18 * counter) + 5 * counter
End If
CbBox.Left = 150
Set cbx = New ComboWithEvent
cbx.SetCombobox CbBox
pComboboxes.Add cbx
Next counter
i = AddScrollBar(Frame1, counter)
End Function
Combobox event handler is working fine but my problem is that I dont know that how can I copy the text of textbox or enable disable the textbox according to the value selected in the dynamic combobox.
Thanks,
Jatin
you'll use this for example :
Me.Controls("ControlName").Visible = True or instead of Visible you can use enable, disable etc..