Access VBA textbox matrix - vba

I would like to insert 1-24 rows into a DB after some VBA precheck. I made an MSAccess form with textbox grid, and name them like this:
I would like only insert the rows with filled "Name". Code:
For i = 1 To 24
namegrid = "Name" & i & ".Value"
If IsNull(namegrid) Then
Else
InsertProduct = "Insert INTO Products (Productname, QTY, IncomingPrice, Desc) VALUES (Name" & i & ".value, QTY" & i & ".value, Price" & i & ".value, Desc" & i & ")"
DoCmd.RunSQL InsertProduct
End If Next i
The If IsNull(namegrid) is not working properly (I think is check the variant instead of the referenced Textbox).
How to do it correctly? (cheking the lenght also tried with no success)
Maybe I have wrong conception...

Related

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

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)

Access Combobox returns wrong values after query

I have the problem, that the Combobox returns strange values after I click a button, which performs a query on that form.
The rowsource is assigned in VBA and I have checked that the value of ST_Id always stays the same
Here is the VBA code:
Private Sub Form_Load()
dYear = Year(Now)
dMonth = Month(Now)
getDate = DateSerial(dYear, dMonth + 1, 0) 'to get the last day of this month
ST_Id = DLookup("[ID]", "ReportingDays", "[ReportingDay] =#" & Format(getDate, "yyyy\/mm\/dd") & "#") 'returns the ID that is saved in ReportingDays-table
Forms!frm_Team!ReportingMonth.RowSource = "SELECT ReportingDays.ID, ReportingDays.MonthText FROM ReportingDays " _
& " WHERE ReportingDays.ID > " & ST_Id - 3 & " AND ReportingDays.ID < " & ST_Id + 10 & ";" 'fills Combobox with values -2 and + 9 months from the actual month
End Sub
When I open the form the first time everything works fine:
But after the form performs a query the combobox values get messed up like this:
Requerying the Combobox in VBA did not change anything.
I hope you can help me with this issue, because I have not been able to solve this for days.
Kind regards
Nick Thomas
This can be done much simpler:
Private Sub Form_Load()
Const RowSource As String = _
"Select ID, MonthText From ReportingDays " & _
"Where DateDiff('m', Date(), ReportingDay) Between -2 And 10"
Me!ReportingMonth.RowSource = RowSource
End Sub

How do I perform a total calculation using price in a combo box?

I am attempting to make a project on visual studio.
I have the following data in a combo box and I was wondering how I would be able to multiply the price (the CStr value) by the number of days the user selects, showing the total in another text box using a calculate button
{cmbPedigreeDog.Items.Add("African Hairless" & CStr(1.14))
cmbPedigreeDog.Items.Add("Boxer" & CStr(0.86))
cmbPedigreeDog.Items.Add("Chihuahua" & CStr(1.83))
cmbPedigreeDog.Items.Add("Dalmation" & CStr(0.65))
cmbPedigreeDog.Items.Add("Eskimo Dog" & CStr(1.14))
cmbPedigreeDog.Items.Add("Farm Collie" & CStr(0.95))
cmbPedigreeDog.Items.Add("GreyHound" & CStr(1.99))
cmbPedigreeDog.Items.Add("Husky" & CStr(1.85))
cmbPedigreeDog.Items.Add("Irish Setter" & CStr(0.65))
cmbPedigreeDog.Items.Add("Jack Russell Terrier" & CStr(1.77))
cmbPedigreeDog.Items.Add("King Charles Spaniel" & CStr(1.02))
cmbPedigreeDog.Items.Add("Labrador Retreiver" & CStr(1.74))
cmbPedigreeDog.Items.Add("Maltese" & CStr(1.47))
cmbPedigreeDog.Items.Add("Pug" & CStr(1.31))
cmbPedigreeDog.Items.Add("Rottweiler" & CStr(2.17))
cmbPedigreeDog.Items.Add("St Bernard" & CStr(1.63))
cmbPedigreeDog.Items.Add("Tibetan Mastiff" & CStr(1.15))
cmbPedigreeDog.Items.Add("Working Sheep Dog" & CStr(0.75))
cmbPedigreeDog.Items.Add("Yorkshire Terrier" & CStr(0.88))
cmbPedigreeDog.Items.Add("Other" & CStr(1.22))}
Not the best way, it requires that all your strings in combobox are of the same pattern with same quantity of delimiters.
Example:
If you use instead of "Boxer" & CStr(0.86) something like "Boxer|" & CStr(0.86) (added just a | symbol), then you can split this string back like this.
line = cmbPedigreeDog.Value
price = CDbl(Split(line, "|")(1))
And some explanations:
Each line of text is a container of symbols. Each can be splitted to array with some delimiter. So the line price = CDbl(Split(line, "|")(1)) can be also written like this:
Dim someArray()
line = "Boxer|" & CStr(0.86)
someArray = Split(line, "|")
' after splitting you have two items in array one is "Boxer" and another is "0.86" (which is text)
' if you follow the pattern in each of your combobox options the price always will be the second one
' so you may refer to second item in array, which is number 1
Price = CDbl(someArray(1))
UPDATE
Another way, as per request in comment. Use two columns combobox. To fill your combobox you have to do following
1 - Go to you ComboBox's properties and set the "ColumnCount" values to 2 (see here how to do it).
2 - This is up to you - you may use the binding with prices on a worksheet as like in topic I gave a link in p.1 or change each line on your code to this pattern:
With cmbPedigreeDog
.AddItem ("Boxer")
.column(1, cbx.ListCount - 1) = 0.86
.AddItem ("Chihuahua")
.column(1, cbx.ListCount - 1) = 1.83
' and so on
End With
3 - To retrieve the price of selected item use such code
If cmbPedigreeDog.ListIndex >= 0 Then
price = cmbPedigreeDog.List(cbx.ListIndex, 1)
Else
MsgBox "item is not chosen"
End If
UPDATE 1
This answer is for VBA, not for Visual Basic WinForm application. For this try to look for a solution like "Multi Column ComboBox"

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.

Using a form control as a field selector in SQL query

I am attempting to build a form ,called UI, that users will select a dimension parameter from a combobox "cmbFilter" and then add a +/- tolerance in a text box "txtTolerance". After selection a part number from a list this should return results for similar part numbers in the the tolorence range for that parameter. The field names in the table are the dimension parameters and are .AddItem to the combobox in the form load code.
Example. Part#1 OD is 5, so I select "OD" as the search parameter then I set a tolerance to +/- 1. The results should show Part#2 with a OD of 6 but not Part#3 with a OD of 7.
I have set a listboxs row source to the query but
no matter what I change in the syntax in this code I get operation or syntax errors. So I assume Im not referencing the form control right, or my logic isn't right?
I have tired the following code in the SQL design view in access.
SQL
SELECT Part_Matrix.Part_Number, Part_Matrix.Customer, Part_Matrix.Large_OD, Part_Matrix.Vent_Opening, & _
Part_Matrix.BPT, Part_Matrix.MFT, Part_Matrix.PD, Part_Matrix.Hat_ID, Part_Matrix.Microfinish, & _
Part_Matrix.Turn_Operations, Part_Matrix.Stud_Holes, Part_Matrix.SH_Dimensions, Part_Matrix.Manufacturer_Holes, & _
Part_Matrix.MH_Dimensions, Part_Matrix.Other_Holes, Part_Matrix.Other_Dimension
FROM Part_Matrix
WHERE [Forms]![UI]![cmbFilter]
BETWEEN (((SELECT [Forms]![UI]![cmbFilter] FROM Part_Matrix WHERE Part_Number = [Forms]![UI]![lbSelected]) - [Forms]![UI]![txtTolerance])
AND ((SELECT [Forms]![UI]![cmbFilter] FROM Part_Matrix WHERE Part_Number = [Forms]![UI]![lbSelected]) + [Forms]![UI]![txtTolerance]))
ORDER BY [Forms]![UI]![cmbFilter] DESC;
I have also tried to write the SQL code in access vba still no luck, the code below was just a simple text, I know its now the same logic as above.
Private Sub btnSearch_Click()
Dim SQL As String
If txtTolerance = "" Then
MsgBox ("No Tolerance Entered")
Exit Sub
ElseIf cmbFilter = "" Then
MsgBox ("No Filter Criteria Entered")
Exit Sub
Else
SQL = "SELECT Part_Matrix.[Part_Number], " & Me.cmbFilter & " " & _
"FROM Part_Matrix" & _
"ORDER BY " & Me.cmbFilter & " DESC;"
Debug.Print SQL
DoCmd.RunSQL SQL
lbFilterResults.RowSource = SQL
lbFilterResults.Requery
End If
End Sub
Try this, using a dlookup instead of SELECT to return the values you want in the BETWEEN statement. I believe the dlookup should return the value for whatever field you select in the combo box. Also, I've simplified to remove the forms!UI statement with a "me" assuming you are running code from the same form. Let me know if this works for ya.
intTarget = dlookup(me!CmbFilter, "PartMatrix", "Part_Number = " & me!LbSelected)
intLower = intTarget - me!txtTolerance
intUpper = intTarget + me!txtTolerance
strSQL = "SELECT * FROM Part_Matrix WHERE " & me!cmbFilter & " " & _
"BETWEEN " & intLower & " AND " & intUpper
In your BETWEEN statement, reference the table's [Large_OD] field and not the form'S.
i.e
WHERE Large_OD
BETWEEN (((SELECT Large_OD FROM Part_Matrix WHERE Part_Number = [Forms]![UI]![lbSelected]) - [Forms]![UI]![txtTolerance])
AND ((SELECT Large_OD FROM Part_Matrix WHERE Part_Number = [Forms]![UI]![lbSelected]) + [Forms]![UI]![txtTolerance]))
ORDER BY " & Me.cmbFilter & " DESC;