How to apply .FindFirst method in VBA for MS Access? - vba

I created a table named tblProduct with 3 fields, Product_ID (short text), Product_Name (short text), Sale_Unit (short text), Product_ID is primary key.
Then there is a form name frm_Product, with cboProductID as combo box, with the row source set to:
SELECT tblProduct.ID, tblProduct.Product_Name, tblProduct.Sale_Unit
FROM tblProduct
ORDER BY tblProduct.Product_Name;
Its bound column set to 1, column count to 3, column width to 0cm;4cm;2cm, there are then 2 textboxes, txtProduct_Name and txtSale_Unit.
Then I wrote the following code for the AfterUpdate event of cboProductID:
Private Sub cboProductID_AfterUpdate()
Set rs1 = CurrentDb.OpenRecordset("tblProduct", dbOpenDynaset, dbSeeChanges)
rs1.FindFirst "ID = '" & "Me.cboProductID.Column(0)" '"
txtProduct_Name = rs1!Product_Name
txtSale_Unit = rs1!Sale_Unit
End Sub
The code stopped at the .FindFirst method.

Try this:
rs1.FindFirst "ID = '" & Me.cboProductID.Column(0) & "'"
if you put quotes around that expression, then you wind up search for a id of Me.cboproductID.Column(0), and I don't think that is the "id" your looking for.

Try this instead : Remove the Quotes around me.cboProdtID.Column(0)

Related

How do I assign an already known integer to a field after the NotInList event is called?

I have this complicated VBA function on a MSAccess form frm_DataEntry. It searches for values which are not in a list. The function is called on de NotInList event of the comboboxes.
When the typed string in combobox cbo_CustomerLocations is not in the list, it will ask if I want to add it to the table tbl_CustomerLocations by Yes/No question. After that it goes from 1st column to the last column and asks if I want to add some new data. The code below shows how to add a CustomerLocation.
The last field CustomerID of my table tbl_CustomerLocations is linked to the CustomerID field of table tbl_Customers
Now my question:
How do I alter my VBA code when the NotInList event is called, and when it reaches the CustomerID column (the last column), It must not ask 'What do you want for CustomerID', but rather automatically selects the CustomerID I previously selected on the same form frm_DataEntry on combobox cbo_Customers?
Private Sub cbo_CustomerLocationID_NotInList(NewData As String, Response As Integer)
Dim oRS As DAO.Recordset, i As Integer, sMsg As String
Dim oRSClone As DAO.Recordset
Response = acDataErrContinue
String_Value = Me.cbo_CustomerLocationID.Text
MsgBold = String_Value
MsgNormal = "Add to list with locations?"
Debug.Print
If Eval("MsgBox ('" & MsgBold & vbNewLine _
& "#" & MsgNormal & "##', " & vbYesNo & ", 'New Location')") = vbYes Then
Set oRS = CurrentDb.OpenRecordset("tbl_CustomerLocations", dbOpenDynaset)
oRS.AddNew
oRS.Fields(1) = NewData
For i = 2 To oRS.Fields.Count - 1
sMsg = "What do you want for " & oRS(i).Name
oRS(i).Value = InputBox(sMsg, , oRS(i).DefaultValue)
Next i
oRS.Update
cbo_CustomerLocationID = Null
cbo_CustomerLocationID.Requery
DoCmd.OpenTable "tbl_CustomerLocations", acViewNormal, acReadOnly
Me.cbo_CustomerLocationID.Text = String_Value
End If
End Sub
Use an If Then block within the loop to check for name of field.
If oRS(i).Name = "CustomerID" Then
oRS(i) = Me.cbo_Customers
Else
sMsg = "What do you want for " & oRS(i).Name
oRS(i).Value = InputBox(sMsg, , oRS(i).DefaultValue)
End If

Set DefaultValue in Access form to last record of a table

I have an Access form with a text box named Box1.
In this text box, I want to have the name of the last product in my table Products as the default value.
My table product has the fields: P_ID and P_Name.
I have coded in VBA in the form:
Me!Box1.DefaultValue = DLookup("P_Name", "Products", "P_ID = DMax("P_ID", "Products")")
However, there is an error in my code as the textbox displays #Name.
The DefaultValue property is a string, so quotes are needed:
Me!Box1.DefaultValue = "'" & DLookup("P_Name", "Products", "P_ID = " & DMax("P_ID", "Products") & "") & "'"

Dlookup reference where name of column being searched is the name of the textbox on my form

I am editing a database created by my predecessor at work. I am creating a "helper" textbox that will pull a value from a table in the same database.
Problem is, in my Dlookup, the name of the column that I am searching is also the name of the textbox on my form that contains the criteria. To change the name of my textbox, I would have to update a lot of code that I did not create. Is there a way around this?
txtgreigeweight = Application.DLookup("[GreigeWeightAvg]", "dbo_TuftingGreigeData", "GreigeRoll# = GreigeRoll#")
I expect the output to be the "GreigeWeightAvg" value from the table.
The output is:
"Syntax error (missing operator) in query expression 'GreigeRoll# = GreigeRoll#'."
Try to concatenate the value:
txtgreigeweight = Application.DLookup("[GreigeWeightAvg]", "dbo_TuftingGreigeData", "[GreigeRoll#] = " & Me![GreigeRoll#].Value & "")
or, it text:
txtgreigeweight = Application.DLookup("[GreigeWeightAvg]", "dbo_TuftingGreigeData", "[GreigeRoll#] = '" & Me![GreigeRoll#].Value & "'")
Include the fully-qualified control name in your selection criteria, e.g.:
txtgreigeweight = Application.DLookup("[GreigeWeightAvg]", "dbo_TuftingGreigeData", "GreigeRoll# = [Forms]![YourFormName]![GreigeRoll#]")
Change YourFormName as appropriate.
At first stop using special characters in field Names...some might think that it improves readability..BUT it won't...its almost a recipe for issues.
So ... just clarify what kind of value is GreigeRoll#
If its numeric (like 1,21,21321) then you should have :
txtgreigeweight = DLookup("[GreigeWeightAvg]", "dbo_TuftingGreigeData", "GreigeRoll# =" & [GreigeRoll#])
On the other hand is alphanumeric (like "A12", "BigGreige","1stG") then it should be :
txtgreigeweight = DLookup("[GreigeWeightAvg]", "dbo_TuftingGreigeData", "GreigeRoll# ='" & [GreigeRoll#] & "'")

MS-ACCESS VBA Multiple Search Criteria

In my GUI, I have several ways to filter a database. Due to my lack of knowledge, my VBA programming has exploded with nested IF statements. I am getting better at using ACCESS now, and would like to find a more succinct way to perform multiple filters. My form is continuous.
Is there a simple way to do the following task (I made a toy model example):
I have a combo box SITE where I can filter by work sites A, B, C. After filtering by SITE, I have three check boxes where the user can then filter by item number 1-10, 11-20, 21-30, depending on what the user selects.
Is there a way to append multiple filters (or filter filtered data)? For example, filter by SITE A, then filter A by item number 1-10?
Currently, for EACH check box, I then have an IF statement for each site. Which I then use Form.Filter = . . . And . . . and Form.FilterOn = True.
Can I utilize SQL on the property sheet to filter as opposed to using the VBA?
What I do for these types of filters is to construct a SQL statement whenever one of the filter controls is changed. All of them reference the same subroutine to save on code duplication.
What you do with this SQL statement depends on what you're trying to do. Access is pretty versatile with it; use it as a RecordSource, straight execute it, and use the results for something else, even just printing it to a label.
To try to modularize the process, here's an example of how I do it:
Dim str As String
str = "SELECT * FROM " & Me.cListBoxRowSource
Me.Field1.SetFocus
If Me.Field1.Text <> "" Then
str = AppendNextFilter(str)
str = str & " SQLField1 LIKE '*" & Me.Field1.Text & "*'"
End If
Me.Field2.SetFocus
If Me.Field2.Text <> "" Then
str = AppendNextFilter(str)
str = str & " SQLField2 LIKE '*" & Me.Field2.Text & "*'"
End If
Me.Field3.SetFocus
If Me.Field3.Text <> "" Then
str = AppendNextFilter(str)
str = str & " SQLField3 LIKE '*" & Me.Field3.Text & "*'"
End If
Me.cListBox.RowSource = str
Variables edited to protect the guilty.
My AppendNextFilter method just checks to see if WHERE exists in the SQL statement already. If it does, append AND. Otherwise, append WHERE.
Making quite a few assumptions (since you left out a lot of info in your question), you can do something like this:
Dim sSql as String
sSql = "Select * from MyTable"
Set W = Me.cboSite.Value
sSql = sSql & " WHERE MySite = " & W & ""
Set X = Me.Chk1
Set Y = Me.Chk2
Set Z = Me.Chk3
If X = True Then
sSql = sSql & " And MyItem between 1 and 10"
If Y = True Then
sSql = sSql & " And MyItem between 11 and 20"
If Z = True Then
sSql = sSql & " And MyItem between 21 and 30"
End If
DoCmd.ExecuteSQL sSql
Again, this is entirely "air code", unchecked and probably needing some edits as I haven't touched Access in some time and my VBA is likely rusty. But it should put you on the right track.
The way i use combobox filtering in access is first I design a Query that contains all the data to be filtered. The Query must contain fields to be used for filtering. QueryAllData => "SELECT Table.Site, Table.ItemNumber, FROM Table;" Then make a copy of the query and Name it QueryFilteredData and Design the report to display the data using QueryFilteredData.
Then create a form with a Site ComboBox, ItemNumber Combo Box, and Sub Report Object and Assign SourceObject the Report Name. Use Value List as the combo box Row Source type and type in the values for Row Source to get it working. To get the report to update I always unassign the SubReport.SourceOject update the QueryFilteredData and then Reassign the SubReport.SourceObject
Combobox_Site_AfterUpdate()
Combobox_ItemNumber_AfterUpdate
End Sub
Combobox_ItemNumber_AfterUpdate()
Select Case Combobox_ItemNumber.value
Case Is = "1-10"
Store_Filters 1,10
Case Is = "11-20"
Store_Filters 11,20
Case Is = "21-30"
Store_Filters 21,30
Case Else
Store_Filters 1,10
End Sub
Private Sub Store_Filters(Lowest as integer, Highest as integer)
Dim SRpt_Recset As Object
Dim Temp_Query As Variant
Dim Temp_SourceObject as Variant
Temp_SourceObject = SubReport.SourceObject
SubReport.SourceObject =""
Set SRpt_Recset = CurrentDb.QueryDefs("QueryFilteredData")
Filter_Combo_Box1 = " ((QueryAllData.[Sites])= " & Chr(39) & Combo_Box1 & Chr(39) & ") "
Filter_Combo_Box2 = (Filter_Combo_Box1 AND (QueryAllData.ItemNumber <= Highest)) OR (Filter_Combo_Box1 AND (QueryAllData.ItemNumber >= Lowest));"
Temp_Query = " SELECT " & Query_Name & ".* " & _
"FROM " & Query_Name & " " & _
"WHERE (" & Filter_Combo_Box2 & ") ORDER BY [Field_Name_For_Sorting];"
SRpt_Recset.SQL = Temp_Query
'Debug.print Temp_Query
SubReport.SourceObject = Temp_SourceObject
End Sub
After the Combo Boxes Work if the Data is going to Change like Site and Item Number then you might want to change the Row Source of the combo boxes to Use a Query that uses Select Distinct Site From QueryAllData. I don't know if Filter_Combo_Box2 step so it may need some correction. Hope this helps.

default value "1484-002" is evaluated as 1482 instead of displaying as string

I have some vba code on my form load that searches for the most recent record in a table then sets the default value for a field on the form to the value from that record.
The values are always in the format of 1484-002. The correct value is being found no problem but when it is displayed on the form it is 1482. This is leading me to believe that it is being treated as a formula and subtracting 2 from 1484 instead of displaying like a string.
The field in the table is set to short text. My form is bound to the table.
Here is a bit of my code:
Private Sub Form_Load()
Dim lastID as Integer
lastID = DMax("ID", "Drilling Detail")
Pattern.DefaultValue = DLookup("[Pattern]", "Drilling Detail", "[ID] = " & lastID)
How do I get the proper 1484-002 displayed?
Text values need delimiters. And maybe handle case of empty table.
Me.Pattern.DefaultValue = "'" & Nz(DLookup("Pattern", "Drilling Detail", "ID = " & Nz(DMax("ID", "Drilling Detail"),0)), "1484-001") & "'"
Can possibly eliminate the intermediate DMax() on the ID field and just DMax() Pattern.
If you really need to increase the sequence by 1:
Dim strNext As String
strNext = Nz(DMax("Pattern", "Drilling Detail"), "1484-000")
Me.Pattern.DefaultValue = "'" & Left(strNext, 5) & Format(Mid(strNext, 6) + 1, "000") & "'"
OnCurrent event is a better location if you need to increment the sequence for multiple records entry.
Advise not to use spaces in naming convention. Better would be DrillingDetail or Drilling_Detail.