hiding/showing multiple columns based on combo box in access - vba

I have a form with a subform which contains upto 100 columns however i only need to see 5 of these columns at any one time. The columns I need to see are always First name and surname plus three other columns based on the choices made in the main form (columns have labels such as HT001, HT002 etc.). One column for each of the three combo boxes available. I have looked everywhere for a solution and keep finding
Me![mycontrol].columnhidden = false
which I can see how it works for one or two columns but my code would need to be rediculously long if each column needs this. In addition to the vast quantity of columns I have 12 different subforms which are choosen from using a select case procedure. I am looking for a simple solution as I am still very much learning VBA.

If you are using a datasheet, you can dynamically set the record source according to the selections made.
Me.RecordSource = "SELECT HT001, HT002 FROM MyTable"
You can refer to the combo box when building your sql:
Me.RecordSource = "SELECT HT001, " & Me.Combo1 & " FROM MyTable"
Some notes on using a listbox with a field list from a table.
You can set the row source type to Field list and the row source to the name of a table:
RowSource: Table1
RowSourceType: Field List
In order to select multiple fields, it is important to set the multiselect property:
MultiSelect : Simple
You can iterate through the selected items in code and build a field list for use in your sql:
For Each itm In Me.List0.ItemsSelected
strSelect = strSelect & "," & Me.List0.Column(0, itm)
Next
strSelect = Mid(strSelect, 2)
sSQL = "SELECT " & strSelect & " FROM Table1"

Related

MS Access use Combo-Box value as Query Criteria

I have a simple form with two combo boxes.
cboProvince which contains a list of provinces [Alberta,Saskatchewan,Quebec]
cboClient which contains a vast list of clients. Each with a Province.
I am attempting to populate cboClient with clients from the province chosen in cboProvince.
My current VBA Code is contained in the "After Update" event in cboProvince and is as follows:
Private Sub cboProvince_AfterUpdate()
Dim SQL As String
SQL = "SELECT tblCustomer.[Customer Name], tblCustomer.Province FROM tblCustomer WHERE Province = '" & cboProvince.Value & "'"
'Apply Row and requery
cboClient.RowSource = SQL
End Sub
I have double checked that my combo boxes are indeed named "cboProvince" and "cboClients"
Something to note as well is the "Province" Column in the "tbsCustomer" is a Combo-Box. I'm unsure if that makes a difference.
Unfortunately the cboClient combo-box does not auto-populate.

Is it possible to make a dynamic sql statement based on combobox.value in access?

I made a form in access with 2 different comboboxes. The user of
This tool can choose in combobox1: the table (which has to be filtered) and the second combobox2 is the criteria to be filtered( for example Language= “EN”) and the output of this query has to be located in tablex.
The problen what I have is that i cant find a solution for passing the value of the combobox1 to the sql statement. The second one is just like: where [language] = forms!form!combo2.value, but the part where i cant find a solution for is: select * from (combobox1 value)? How can i pass the combobox value as table name to be filtered? Can anyone please help me?
You can't have the table name in the WHERE clause of your query (there might be a hacky way to do it, but it should be discouraged at any case).
If you want to select data from 1 of a number of tables, your best bet is to generate SQL dynamically using VBA. One way to do this (especially if you want/need your query to open in Datasheet View for the end user) is to have a "dummy" query whose SQL you can populate using the form selections.
For example, let's say we have 2 tables: tTable1 and tTable2. Both of these tables have a single column named Language. You want the user to select data from either the first or second table, with an optional filter.
Create a form with 2 combo boxes: One for the tables, and one with the criteria selections. It sounds like you've already done this step.
Have a button on this form that opens the query. The code for this button's press event should look something like this:
Private Sub cmdRunQuery_Click()
Dim sSQL As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
If Not IsNull(Me.cboTableName.Value) Then
sSQL = "SELECT * FROM " & Me.cboTableName.Value
If Not IsNull(Me.cboFilter.Value) Then
sSQL = sSQL & vbNewLine & _
"WHERE Language=""" & Me.cboFilter & """"
End If
Set db = CurrentDb
Set qdf = db.QueryDefs("qDummyQuery")
qdf.SQL = sSQL
DoCmd.OpenQuery qdf.Name
End If
End Sub
Note how the SQL is being generated. Of course, using this method, you need to protect yourself from SQL injection: You should only allow predefined values in the combo box. But this serves as a proof of concept.
If you don't need to show the query results, you don't need to use the dummy query: You could just open a recordset based on the SQL and process that.
If you run the code in the afterupdate event of the combobox you can set an SQL statement like this:
Private Sub combobox2_AfterUpdate()
someGlobalVar = "Select * FROM " & me.combobox1.value & " WHERE language = " & _
me.combobox2.value
End Sub
And then call the global with the SQL string wherever you need it.

Passing multiple criteria to query in access via VBA code

I am working on a Access database that I inherited from the person working on it before me. I am novice at this and learning as I go along.
Background:
I am working with a database of experimental data.
I am trying to create a search and export form which will allow the the user to search for a particular data set and then export that to an excel sheet. It will also let the user filter the search so as to write only specific values into the excel file.
My data base has 2 main sub tables differentiating the kind of experiments.
I use a list box that allows the user to choose which table he/she wants to search.
based on this selection two additional listboxes get populated with the relevant options
the options are "Author Name" and a "Number ID"
Upto this point everything works
if table 1 is selected one set of author names and number ids are populated in the list boxes and the same is true if table 2 is selected.
the author name and also the number id list boxes are simple multiselect.
I loop over the list box selection to get all the values selected
I then create the SELECT and IN statement.
This works like a charm for the number id (when i execute with only 1 list box).
However I get an error if i try to create a query statement as follows:
SELECT * FROM tbl1 [Number_ID] IN (a,b,...) AND
SELECT * FROM tbl1 [AUTHOR_NAME] IN ("xyz", "abc",....)
where Number_ID is an Integer and
Author_Name is text
Solution:
strSQL = "SELECT * FROM tbl1 WHERE "
strWhere = "[Number_ID] IN (1, 2, 3, ...)"
strSQL = strSQL & strWhere
strSQL1 = " AND "
strWhere1 = "[Author_Name] IN ("xyz", "abc", ...)"
strSQL = strSQL & strSQL1 & strWhere1
This generates a query string as follows
"SELECT * FROM tbl1 WHERE [Number_ID] IN (1, 2, 3, ...) AND [Author_Name] IN
("xyz", "abc", ...)"
which can be passed to your qryDef variable to create a query.

What to do with VBA Query Result

I have a query within access that selects all the contacts for a particular company based on the CompanyID Field. And on my form i have a selection of labels of which will be populated with the query result. However i'm a little stuck on how i should populate the labels, as there will be more than one contact returned from the query..
The Query
ConactData = "SELECT * FROM Contacts WHERE CompanyID = " & CompanyValue & ";"
Obviously i can do
Set rst = CurrentDb.OpenRecordset(ContactData, dbOpenSnapshot)
Me.lblTitle.Caption = rst!Title
Me.lblFirstName.Caption = rst!FirstName
Me.lblLastName.Caption = rst!LastName
Me.lblEmail.Caption = rst!Email
Me.lblMobileNumber.Caption = rst!MobileNumber
But this will just select the first result from the table, how then, can i move onto the next result? If i'm right in thinking the MoveNext method will simply go to the next record in the table, not the query result?
Why use labels? Just build the form bound to the table.
Then in your code go:
Me.RecordSource = "SELECT * FROM Contacts WHERE CompanyID = " & CompanyValue & ";"
This means you don’t need a bunch code to fill out the form, it is done for you. And your example would not allow editing of data either. To write a bunch of code when all the display of data is automatic is a waste of developer time and resources.
In fact, why not leave the form bound to the table, and then use a where clause to open the form
eg:
docmd.openform "frmContacts",,,"CompanyID = " & CompanyValue
So it not clear why you writing all that code and doing handstands - it simply not required.

MS Access Query from form for multiple records in text box

I have created a form in Access which queries a single record in a set date range. This works beautifully. My question is how can I query multiple records from a form text box.
Something Similar to the SQL function
IN ('XXX','XXX','XXX')
I want my users to be able enter multiple values on the form and it will spit out the corresponding Data.
Try the Split() function. Something like this:
Dim arr() As String
Dim MySQL as String
If Len(Me!MyTextbox) > 1 Then
MySQL = "SELECT * FROM MyTable WHERE MyField in ("
arr = Split(Me!MyTextbox.Text, ",")
For i = LBound(arr) To UBound(arr)
MySQL = MySQL & "'" & arr(i) & "', "
Next
MySQL = Left(MySQL, Len(MySQL) - 2) & ")"
Me.RecordSource = MySQL
Else
MsgBox "There are no values to search for."
EndIf
You would just loop through the array and add each value to a WHERE string. You would have to instruct your users (via a label on the form) to separate values using a comma.
When you want to allow multiple entries it's generally better to have a datasheet subform where users can enter data one per row. Then you use the subform data in queries just like a regular table.