MS Access VBA - Loop Recordsets - vba

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

Related

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.

Access Filter By Field

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.

simple use recordset to find text box value on report

I'm trying to learn how to use recordsets in VBA and starting here. I want to lookup the value from the ProductVars table and populate to a text box on a report for each record [ProductID].
The value I want is where Field [Name]="Hinging" and I need it to send the value from the Field [Value] to the txtHinge text box on the report.
Here is my current code.
Private Sub Report_Load()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
'Open a table-type Recordset
Set rs = db.OpenRecordset("ProductVars")
'Find the value of Hinging from the Name field Name and populate to txtHinge
for the ProductID
Do Until rs.EOF
Me.txtHinge = rs!Name.Hinging.Value
rs.MoveNext
Loop
End Sub
Any help would be greatly appreciated.
In textbox ControlSource:
=DLookup("[Value]", "PRODUCTVARS", "[Name]='Hinging' AND ProductID=" & [ProductID])
Or if multiple dynamic parameters must be considered:
=DLookup("[Value]", "PRODUCTVARS", "[Name]='" & [Name] & "' AND ProductID=" & [ProductID])
If the latter is the case, possibly could just include the PRODUCTVARS table in the report RecordSource with a compound join.

ComboBox max records reached

I have a table in MySQL accessed through a linked table (via ODBC) in Microsoft Access 2013.
This table contains over 124,000 records and I need a ComboBox in a form to be able to search through the UPC column.
This is the query that is the current datasource for the ComboBox:
SELECT [ID], [UPC_Case], [Description] FROM itemlist ORDER BY [UPC_Case];
This works perfectly except that the table view under the ComboBox won't go past record number 62287 (however the auto-fill still works for records that the table can't see), is there a way to make it able to view all the records?
Access ComboBoxes have a maximum record count of 65535.
To circumvent this, I found an article that gave me the groundwork required to write a function that sets the rowSource dynamically once a certain number of characters have been typed.
This is the function that sets the rowSource. I refactored the code so that it can be used on any comboBox in any Form with any Query.
Dim inputStub As String
Function ComboLimiter(targetCombo As ComboBox, minChars As Integer, Query As String, searchField As String)
Dim inputStr As String: inputStr = targetCombo.Text 'Set input string
Dim newStub As String: newStub = Nz(Left(inputStr, minChars), "") 'Set first n characters of targetCombo.Text
If newStub <> inputStub Then 'If first n chars are the same as previously, do nothing.
If Len(newStub) < minChars Then
'Remove the RowSource
targetCombo.RowSource = Query & " WHERE (False);"
inputStub = ""
Else
'New RowSource
targetCombo.RowSource = Query & " WHERE (" & searchField & " Like """ & newStub & "*"") ORDER BY " & searchField & ";"
inputStub = newStub
End If
End If
End Function
And the function can be bound to the ComboBox change event like this:
Private Sub UPCCombo_Change()
Call ComboLimiter(Me.UPCCombo, 1, _
"SELECT ID, UPC_Case, Description FROM itemlist", "UPC_Case")
End Sub
There's a known bug where there are sometimes issues with large recordsets like this. Are you sorting on a text based field? Try removing the sort if so and seeing if it fixes the issue.

How can I add criteria based on a form field to an Access query?

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)