Just curious if filtering fields is a possibility in Access? Or if there is VBA code that allows the "Show" Box in the query to be checked or unchecked based on an if statement?
Basically I have about 80 fields in my database and I want to create a table with only 3 of them, based on a value in a combo box. 2 are always the same, and the 3rd would be based on a combo box.
Can I do that?
You could do this by altering the SQL of the query object you want to modify. So if your query object is named "qryMyQ", and your combo box object is named "cboDropDown", then the VBA would be the combo box's AfterUpdate event and would look like this:
Private Sub cboDropDown_AfterUpdate()
Dim qryDef As QueryDef
Dim sql As String
Set qryDef = CurrentDb.QueryDefs("qryMyQ")
sql = "SELECT [Column1], [Column2], [" & cboDropDown.Value & _
"] FROM yourTableName " & _
" WHERE [" & cboDropDown.Value & "] = ""applicable"""
Debug.Print sql 'This line will allow you to troubleshoot the SQL that is to be executed.'
qryDef.sql = sql
Set qryDef = Nothing
End Sub
Just a note here; but you'd want to make sure that users cannot add or edit the combo box options to avoid sql injections. Not sure how friendly your userbase is.
Related
Essentially I would like to update a subforms column values with a name found in a combo box.
A table called "tbl_jobs" is the source behind the subform, the column I am trying to update is called "Person_Name".
The combo box is called "PersonCombo" .
I am working on creating a query called "updateRecord" using the Access query designer that is executed by the button "updateButton"
The following is how the query will be executed:
DoCmd.OpenQuery "updateRecord"
The content of the query is what I am having trouble with:
UPDATE tbl_jobs SET Person_Name = '" & PersonCombo & "' WHERE [Select] = True
Instead of filling the column data with the values from the chosen name in "PersonCombo" like Jamie, Mickey, Haley, etc. (values from PersonCombo) it just says " & PersonCombo & "
What is wrong with my syntax?
If this is a saved query, it doesn't know about the current form.
You need to use the full path to the control, but no concatenation, e.g.
UPDATE tbl_jobs SET Person_Name = Forms!myForm!PersonCombo WHERE [Select] = True
If the combo box is on a subform, refer to:
Forms: Refer to Form and Subform properties and controls
e.g. Forms!Mainform!Subform1.Form!ControlName
I do not believe you can pass a variable to a saved query. Instead build the query in code and run it:
dim SQL as string
PersonCombo = "thePerson"
SQL = "UPDATE tbl_jobs SET Person_Name = '" & PersonCombo & "' WHERE [Select] = True"
DoCmd.RunSQL SQL
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.
I am wondering if anyone could direct me to a good tutorial on how to develop loops. Basically I have a "tblmachines" with columns ID, MachineName and Checkbox. What I want to create is an on click event, VBA will take todays date and input that into "tblloop" column "LoopDate", and then add all machines in "tblmachines" which have their checkbox selected into "tblloop" column "loopMachines".
If you're inserting records from tblmachines table to tblloop table based on the check box criteria use the below code:
Sub Btn_Click()
Dim StrQry As String
StrQry = "insert into [tblloop] ([LoopDate], [loopMachines]) select # " & VBA.Now & "# as [LoopDate], [MachineName] from [tblmachines] where Checkbox = 'True'"
Currentdb.Execute StrQry
End Sub
How do I get an operator to work in a query criteria based on a form field. Ideally I would like it to be something like:
IIf([Afloat]="No",<[Forms]![DASF]![Text222],"")
When I remove the operator it finds anything exactly to the criteria in that field but the moment I try to put an operator like greater than or less than it does not work. I am trying to find all records less than the value in that form field.
Any advice on how I can fix this? Or is it not possible in MS Access?
QBF (Query By Form) can't accept operators in the formula. Your only option is to write the query on the fly. You can use the CreateQueryDef method to define the SQL in a specific query, and attach your form or report to the specific query name.
Something like:
Dim db as Database
Dim rec as Recordset
Dim qdf As QueryDef
Dim strSQL as String
Set db = CurrentDB
On Error Resume Next
'First, delete the query if it exists
db.QueryDefs.Delete "MyQueryName"
'Then, set up the query string
strSQL = "Select * From MyTable Where MyField < " & [Forms]![DASF]![Text222] & " and [Afloat] = 'No' "
strSQL = strSQL & "UNION "
strSQL = strSQL & "Select * From MyTable Where MyField = '' and [Afloat] <> 'No' "
'Now, recreate the query
Set qdf = db.CreateQueryDef("MyQueryName", strSQL)
DoCmd.OpenQuery qdf.Name
You could try changing the first criteria to:
>IIf([Afloat]="No",[Forms]![DASF]![Text222])
And then add a second criteria below it in the Or line:
=IIf([Afloat]<>"No","")
I ended up solving my problem by separating it into two separate queries. Below are my steps:
Instead of having a logical expression to decide I separated it into
FLOAT and NONFLOAT queries.
Then I created a command button to open
each query depending on the criteria in a combo box (yes or no).
Here is the code:
Private Sub Command2_Click()
DoCmd.SetWarnings False
If Me.Combo272 = "Yes" Then
DoCmd.OpenQuery "DASF_AGED_AS1_FLOAT", acViewNormal, acEdit
Else
DoCmd.OpenQuery "DASF_AGED_AS1_NONFLOAT", acViewNormal, acEdit
End If
End Sub
This created another problem, I was still unable to reference the txt boxes necessary for my query criteria. To solve this, I made all the text boxes unbound by using the below VBA to auto populate the text boxes based on another combo box. Here is the VBA I used:
Me.Text220 = DLookup("REGION", "TDD_TABLE", "[ID]= " & Me.Combo236)
I want to be able to extract details from an Access database to my excel workbook. I have created a userform where the user enters the policy number and then click a command button that should provide a another userform with a dropdown list of all the quotes for that policy
The access database table contains multiple rows for a given quote but I want to be able to extract a list of unique quote ids for the policy from which the user can select the quote they want to load the details for.
Below is an extract from the Access database (table name qteVehicleDetails, database name QuoteDB)
Database Extract
Private Sub CommandButton1_Click()
Dim dbQuoteDB As Database
Dim rTemp As Recordset
Dim sSQL As String
Set dbQuoteDB = OpenDatabase(QuoteDB, False, False, "MS Access;PWD=***")
sSQL = "SELECT qteVehicleDetails.* FROM qteVehicleDetails WHERE (qteVehicleDetails.policyno=" & LoadQuoteDetails.Controls("PolicyNo").Value & " AND qteVehicleDetails.Class=" & LoadQuoteDetails.Controls("Class").Value & ");"
Set rTemp = dbQuoteDB.OpenRecordset(sSQL)
Do Until rTemp.EOF
???
rTemp.MoveNext
End Sub
I want to be able to extract a list of unique quotes ids for a given policy (you will see from the database extract that there are duplicates)
Then I want to save this as a range which can be used to populate the combo box in the second userform.
"SELECT DISTINCT qteVehicleDetails.* FROM qteVehicleDetails WHERE (qteVehicleDetails.policyno=" & LoadQuoteDetails.Controls("PolicyNo").Value & " AND qteVehicleDetails.Class=" & LoadQuoteDetails.Controls("Class").Value & ");"
you can try add 'distinct' in your sql script