MultiSelect Listbox issues - ms-access

I am having an issue making a listbox into a multiselect listbox. I understand that the code to make a listbox multiselect is:
[forms]![formname]![listboxname].multiselect=2
However when I run this in Private Sub Form_Load() I get run-time error '2448' You can't assign a value to this object.
I guess I don't understand how to make a listbox multiselect, but I am pretty sure I understand how to use the multiselect listbox in VBA.
Any help on how to use the above code to actually change the listbox to multiselect would be appreciated.

From Microsoft Office Help on property MultiSelect:
This property can be set only in form Design view.
Set this property in Form Design, and don't try to change it in code.
Some examples of working with MultiSelect:
' Retrieve all selected values
Public Function ListBoxGetMultiSelect(ByVal rListBox As Access.ListBox) As String
Dim v As Variant
Dim vList As Variant
vList = ""
With rListBox
For Each v In .ItemsSelected
vList = vList & .Column(0, v) & vbCrLf
Next
End With
ListBoxGetMultiSelect = vList
End Function
' clear all selected values
Public Sub ListBoxClearSelection(ByVal rListBox As Access.ListBox)
Dim v As Variant
With rListBox
For Each v In .ItemsSelected
.Selected(v) = False
Next
.Value = Null
End With
End Sub

I've found a way to set Multiselect Property via Vba Code:
DoCmd.SetWarnings = False
DoCmd.OpenForm myformname, acDesign
Forms(myformname).SetFocus
Forms(myformname).Controls(List3).MultiSelect = 0
DoCmd.Close acForm, myformname
DoCmd.SetWarnings = True

Related

Setting Combobox Value With VBA MS Access

I am trying to make a module to pass a single result of a query into a Combobox to be populated/displayed immediately on Form_Load event, but I keep getting the following error: Run-time error '2465' "Microsoft Access can't find the field 'MyCombo' referred to in your expression"
Query result is tested and returning the proper value. the problem is in the reference call to the MyCombo combobox.
This is my code below:
Public Function getSetRefNo() As String
Dim rs1 As DAO.Recordset
Dim currentformName As String
currentformName = Screen.ActiveForm.Name
Dim docidrefnoquery As String
Dim dociddefaultvalue As String
Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT ColA FROM TblA WHERE ColC = " & Forms(currentformName)![Combo25])
Do Until rs1.EOF = True
docidrefnoquery = rs1(0)
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
dociddefaultvalue = DLookup("RefNo", docidrefnoquery) 'RefNo here is the target column in the Query
Forms(currentformName)![MyCombo] = dociddefaultvalue 'MyCombo here is the Combobox Name
Debug.Print docidrefnoquery & " - " & dociddefaultvalue
End Function
on the targeted form, I use this code:
Private Sub Form_Load()
Call getSetRefNo
End Sub
after opening the targeted form, I receive the above mentioned error. I don't know what's wrong I tried to trace everything and it seems to be fine, I used the same chunk of codes in other places and worked fine. don't know what's wrong here to be honest. I would be grateful if you could help me elaborate what's going on.
I had to alter the form_load event like the following:
Private Sub Form_Load()
Me.TimerInterval = 30
End Sub
Private Sub Form_Timer()
Me.TimerInterval = 0
Call getSetRefNo
End Sub

How to create a ListBox with checkboxes in a Microsoft Access Form?

I'm new to Microsoft Access and would like to create a ListBox (or ListView) with checkboxes, however I can't find any native way for doing so.
My intention is to display a list of values and have some of the values checked depending on what value is selected in a ComboBox on the form.
Please note that I'm needing such a control for a form and not a table (for which there's this "multivalued lookup field"). (Besides if there's a way to create a subform with a table with just the multivalue-column that reacts to what's selected in the ComboBox.)
An ordinary list box with the "Multi Select" property set to "Simple" doesn't display checkboxes.
I also can't see the "ListStyle" property described here.
Maybe it's somehow possible to display two columns in the ListBox of which the first is rendered as checkbox?
You can use the ListView control. It is located under ActiveX Controls, the full name is Microsoft ListView Control, version 6.0.
It has a separate set of properties: right-click -> ListViewCtrl object -> Properties, in there is the Checkboxes property.
To fill the listview with data, see e.g. ACC: Sample Function to Fill a ListView Control
More info: Using the ListView Control
Edit
To comfortably work with the Listview object model, set a reference to Microsoft Windows Common Controls 6.0 = C:\Windows\SysWOW64\MSCOMCTL.OCX on my Windows7 64bit.
Edit 2
I use a TreeView with checkboxes. Each Node has a Checked property, that checks or unchecks its checkbox. Where the Treeview has Nodes, the Listview has ListItems, but they have a Checked property too.
Simplified code for Treeview (without hierarchies):
Dim oTree As TreeView
Dim oNode As Node
Dim RS As Recordset
Set oTree = Me.myTreeView.Object
oTree.Nodes.Clear
Set RS = DB.OpenRecordset("My query to fill the treeview")
Do While Not RS.EOF
Set oNode = oTree.Nodes.Add(key:=RS!foo, Text:=RS!bar)
oNode.Checked = (RS!someValue > 0)
RS.MoveNext
Loop
RS.Close
You can't modify a listbox of Access like that, but you can customize a subform in datasheet view to mimic such a listbox.
To display more or less fixed values, create a small local table to be bound by the form and fill it with the values you need.
So got it working now with the help of Andre's answer:
First, as the ListView is dependent on the currently selected item of a table I'm populating it via the Form_Current event of the table. (Simply by Call Forms.Item("MainForm").PopulateListView)
Here's the working PopulateListView method (note that you need to reference Microsoft Windows Common Controls 6.0 first):
Public Sub PopulateListView()
On Error GoTo ErrorHandler
Dim intToCount As Integer
Dim intCount1 As Integer
Dim intCount2 As Integer
Dim intToCount2 As Integer
Dim intCount12 As Integer
Dim intCount22 As Integer
Dim NewLine As Object
Dim db As Database
Dim rs As Recordset
Dim colNew As Object
Dim s As String
' Clear the ListView control.
Forms![MainForm].[SubForm].Form.[ctlListView].ListItems.Clear
Forms![MainForm].[SubForm].Form.[ctlListView].ColumnHeaders.Clear
' Set Variables.
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT A, B, IsChecked . . .")
' Set Column Headers.
Set colNew = Forms![MainForm].[SubForm].Form.[ctlListView].ColumnHeaders.Add(, , "A", 2000)
Set colNew = Forms![MainForm].[SubForm].Form.[ctlListView].ColumnHeaders.Add(, , "B", 4000)
' Set Total Records Counter.
rs.MoveLast
intToCount = rs.RecordCount
rs.MoveFirst
' Loop through recordset and add Items to the control. Twice as a workaround to sort by checkbox.
For intCount1 = 1 To intToCount
If (rs(2).value = 1) Then
If IsNumeric(rs(0)) Then
s = Trim(Str(rs(0).value))
Else
s = Trim(rs(0).value)
End If
Set NewLine = Forms![MainForm].[SubForm].Form.[ctlListView].ListItems.Add(, , s)
If IsNull(rs(1)) Then
NewLine.ListSubItems.Add Text:=""
Else
NewLine.ListSubItems.Add Text:=rs(1).value
End If
NewLine.Checked = True
End If
rs.MoveNext
Next intCount1
' Set Total Records Counter.
rs.MoveLast
intToCount2 = rs.RecordCount
rs.MoveFirst
For intCount12 = 1 To intToCount2
If (rs(2).value = 0) Then
If IsNumeric(rs(0)) Then
s = Trim(Str(rs(0).value))
Else
s = Trim(rs(0).value)
End If
Set NewLine = Forms![MainForm].[SubForm].Form.[ctlListView].ListItems.Add(, , s)
If IsNull(rs(1)) Then
NewLine.ListSubItems.Add Text:=""
Else
NewLine.ListSubItems.Add Text:=rs(1).value
End If
End If
rs.MoveNext
Next intCount12
Exit Sub
ErrorHandler:
' Err 3021 = no current record. Err 2455 = happens at necessary first call of method and couldn't catch in code.
If Err = 91 Or Err = 3021 Or Err = 2455 Then
Resume Next
Else
If Err <> 94 Then
' Otherwise display the error message.
MsgBox "Error: " & Err.Number & Chr(13) & Chr(10) & Err.Description & vbCrLf & "(PopulateListView)"
End If
End If
End Sub
Then for saving I'm using this:
For Each Item In Forms![MainForm].[SubForm].Form.[ctlListView].Object.ListItems
If Item.Checked = True Then
'Use Item here
End If
Next

VBA Access Textbox returning Null Value

I have a VBA Access userform. In this useform there is a textbox with the name txtSearch_POBOX. I'm trying to get its value using the code below:
Private Sub txtSearch_FirstName_Change()
MsgBox ([Form_Client List].txtSearch_POBOX.Value)
End Sub
But this is constantly returning NULL. When even when there is a value inside the text box. Any ideas?
Your reference is wrong. It should read:
MsgBox Forms![Client List]!txtSearch_POBOX.Value
As it could be empty, you should use:
MsgBox Nz(Forms![Client List]!txtSearch_POBOX.Value)
remember that if you want to intercept the text box value while digiting, until you "validate" the content change (e.g. losing focus) the .Value property is not updated.
For instance I used a text box to make a running filter of a submask: I wanted to filter the submask while digiting.
To do this you need to use the .Text property.
In the following example I make a running filter of a list of Publishers:
Private Sub txtNameFilter_Change()
On Error Resume Next
Dim strFilter As String
If Not IsNull(Me.txtNameFilter.Text) Then
strFilter = "Publisher LIKE '*" + Me.txtNameFilter.Text + "*'"
Me.Filter = strFilter
Me.FilterOn = True
Me.txtNameFilter.SelStart = Len(Me.txtNameFilter.Text)
End If
End Sub
Bye
Wiz

Empty combobox values when access form loads vba

I want to empty the combobox every time when form loads. Using the below code
Private Sub Form_Load()
combo1.RowSource = ""
End Sub
But Combobax is not emptying.
Your code is setting the rowsource of the combo box not the value. The combo box can be cleared by setting the value directly.
Private Sub Form_Load()
combo1 = ""
End Sub
Recommend you clear using the following:
Me.comboBoxName.RowSource = ""
Me.comboBoxName = ""
I used below and worked with me
me.combo2.value=""

How to create a new form instance using the name of the form as a String

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.