How to populate combo box from a select Query using VB in access? - vba

I'm new to VB and trying to populate combo box in access from a select query's result which is getting value from another combo box and the code that i'm trying is:
Private Sub addPartsButtonForm_Click()
ssql = "SELECT * FROM EquipmentTbl WHERE [EquipmentID] = '" & Me.equipmentCombo.Column(0) & "'"
Me!comboParts = ssql
Me.comboParts.Requery
End Sub
and when i press the button i got the following result in combo box:
SELECT * FROM EquipmentTbl WHERE [EquipmentID] = '34'
though its giving me the exact equipmentID but expected is something else other than that. Please help me

Set the combo RowSource. Also, no need for quotes in case field is Number.
Dim sSql As String
sSql = "SELECT * FROM EquipmentTbl WHERE [EquipmentID] = " & Me.equipmentCombo.Column(0)
Me.comboParts.RowSource = ""
Me.comboParts.RowSource = sSql

Related

Using values from multi-select list box in MS Access Query

I have one table in my MS Access data base named COA_Map. I also have a form with a multi-select list box. When the values are selected, vba turns them into a string and updates a text box with the string. I want to use the textbox string as a variable in a query.
This is my query:SELECT * FROM COA_Map WHERE (COA_Map.ASL IN ( [Forms]![Multi-Select Search]![TextASL].Text ) );
This returns empty results. When I copy and paste the text box values into the query like this:
SELECT * FROM COA_Map WHERE (COA_Map.ASL IN ( 2.1,2.3,2.4 ) );
I get the expected results. I tried [Forms]![Multi-Select Search]![TextASL].Value and [Forms]![Multi-Select Search]![TextASL] but that gives an error "This expression is typed incorrectly, or it is too complex"
I also tried using "OR" clause instead of "IN". I changed the VBA to return this string:
to build this query: SELECT * FROM COA_Map WHERE COA_Map.ASL = [Forms]![Multi-Select Search]![TextASL] ;
This returns the same empty results. When I paste the textbox values into the query like this: SELECT * FROM COA_Map WHERE COA_Map.ASL = 2.1 OR COA_Map.ASL = 2.2 OR COA_Map.ASL = 2.3 ;
, I get expected results.
When only one value is selected in either version of the query, I get expected results.
I can't figure out why the the query will not return results when reading from the text box with multiple values selected.
Here is a generic example to get you going in the right direction.
Private Sub cmdOK_Click()
' Declare variables
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim varItem As Variant
Dim strCriteria As String
Dim strSQL As String
' Get the database and stored query
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryMultiSelect")
' Loop through the selected items in the list box and build a text string
For Each varItem In Me!lstRegions.ItemsSelected
strCriteria = strCriteria & ",'" & Me!lstRegions.ItemData(varItem) & "'"
Next varItem
' Check that user selected something
If Len(strCriteria) = 0 Then
MsgBox "You did not select anything from the list" _
, vbExclamation, "Nothing to find!"
Exit Sub
End If
' Remove the leading comma from the string
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
' Build the new SQL statement incorporating the string
strSQL = "SELECT * FROM tblData " & _
"WHERE tblData.Region IN(" & strCriteria & ");"
' Apply the new SQL statement to the query
qdf.SQL = strSQL
' Open the query
DoCmd.OpenQuery "qryMultiSelect"
' Empty the memory
Set db = Nothing
Set qdf = Nothing
End Sub

Microsoft Access VBA Populating a field of a percentage of total records

When I click on button command9 I want to use the count function to count how many records matching combo7 and Insp_Cat = 1, then calculate 20% of the total records. Then using the Update statement update the field Insp_Type to "C" ,limiting the number of records to 20% of total records previously calculated.
This is the code I have to date but getting a syntax error on the count line.
Private Sub Command9_Click()
Dim strSql As String
Dim Rec_Qty As Integer
Dim Rec_Perc As Integer
'Return record count for all records in Tbl_Inspections matching WO_ID in Combo7 and Insp_Cat =1
Rec_Qty = Count (WO_ID & Insp_Cat) Where [WO_ID]= Me.[Combo7]& [Insp_Cat]=1 From Tbl_Inspections
Rec_Per = Rec_Qty * 0.2
'Update records for "C" 20% records using Rec_Per value in limit function of Update command
strSql = "Update Tbl_Inspections"
strSql = strSql & "Set Insp_Type = 'C' WHERE WO_ID = Me.Combo7 & Insp_Cat = 1 & Limit = Rec_Per"
CurrentDb.Execute strSql
End Sub
Can anyone help?
Can't use Count() function in VBA, only within a query or in textbox on form or report.
DCount() and other domain aggregate functions used in VBA.
Concatenate literal text and variables.
Rec_Qty = DCount("*", "Tbl_Inspections", "[WO_ID]= " & Me.[Combo7] & " AND [Insp_Cat]=1")
CurrentDb.Execute "Update Tbl_Inspections Set Insp_Type = 'C' WHERE WO_ID = " & Me.Combo7 & " AND Insp_Cat = 1 AND Limit = " & Rec_Per

MS Access : Add Select All to combo box

i tried this :
To add an (All) item to the list, return to Design view and select the combo box control. Then, replace the Row Source property with the following SQL statement:
SELECT City FROM Employees
UNION SELECT "(All)" FROM Employees;
from here : https://msdn.microsoft.com/en-us/library/aa140084%28v=office.10%29.aspx
My Sql statement looks like this :
SELECT LastName FROM Employee
UNION SELECT "(All)" FROM Employee;
I can see the (All) in my drop down,the problem is when I select the Option (All) i receive a blank page.
Am I missing something? Do I need some VBA Code ? This is my current Code:
Private Sub cboFilter2_AfterUpdate()
Dim myFilter As String
myFilter = "Select * from Employee_Filter_Query where ([LastName] = '" & cboFilter2 & "')"
Me.Employee_Filter_subform.Form.RecordSource = myFilter
Me.Employee_Filter_subform.Form.Requery
End Sub
Br,
You likely do not have a last name of "(All)" and SQL doesn't automatically know to select everything when you pick "(All)" form the combobox. You'll need to adapt your query:
"Select * from Employee_Filter_Query where ([LastName] = iif('" & cboFilter2 & "'='(All)',[LastName],'" & cboFilter2 & "'))"
WHat this will do is look for the combobox to say "(All)" and if it does then match [LastName] = [LastName] which will always be true and return all records, otherwise it will match [LastName] against your filter and act like normal.
An alternative is to set up like this:
If cboFinter2 = "(All)" Then
myFilter = "Select * from Employee_Filter_Query"
Else
myFilter = "Select * from Employee_Filter_Query where ([LastName] = '" & cboFilter2 & "')"
End If

Use a ComboBox Value as part of an SQL Query? (MS Access 2010-2013)

I have a Database that we use to create Bills of Materials from Tags in AutoCAD. Because of the nature of this, I need to create 3 separate queries. One for our "Steel", one for our
"Non-Steel", and one for our "Uncut Tubes".
The SQL for the Queries is as follows:
Steel:
SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([CUT-SHEET-WEIGHT]) AS [SumOfCUT-SHEET-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT]
FROM [13-1302 Cut-Lengths];
Non-Steel:
SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=23));
Uncut Tubes:
SELECT DISTINCT [13-1302 Cut-Lengths].[TOTAL-LENGTH-WEIGHT], [13-1302 Cut-Lengths].MATERIAL, [13-1302 Cut-Lengths].ORDER
FROM [13-1302 Cut-Lengths]
ORDER BY [13-1302 Cut-Lengths].ORDER;
I have a ComboBox that chooses the Job Number (For Main and Uncut Tubes, e.g. 13-1302) and a Textbox that displays the JobID (For Non-Steel).
Is there a way that I can set up the SQL shown above to look at the ComboBox and TextBox Values, instead of me having to change them by hand?
EDIT
I figured it all out now. (Thank you Elias)
Basically, I cannot use a Field on a table as a RecordSource in SQL, in other words, Combo26 cannot be the Table in an SQL Query. HOWEVER, what CAN be done is to use VBA to inject that value into an SQL Definition, then use that definition as a Recordsource.
I will place the code for my Button below so anyone can use it and reference it:
Private Sub Command27_Click()
Dim dbs As Database
Dim rstSQL As DAO.Recordset
Dim strSQL As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim Field As String
Set dbs = CurrentDb
Field = [Forms]![frmBOM_Combined]![Text26].[Value]
strSQL = "SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & ";"
strSQL2 = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight FROM tbl2013BOM GROUP BY tbl2013BOM.fJobID HAVING (((tbl2013BOM.fJobID)= " & [Forms]![frmBOM_Combined]![Combo25].[Value] & "));"
strSQL3 = "SELECT DISTINCT [TOTAL-LENGTH-WEIGHT], [MATERIAL], [ORDER] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & " ORDER BY [ORDER];"
Debug.Print strSQL
Debug.Print strSQL2
Debug.Print strSQL3
DoCmd.OpenForm ("frmEstWeight")
Forms!frmEstWeight.RecordSource = strSQL
Forms!frmEstWeight.frmTestBomWeight.Form.RecordSource = strSQL2
Forms!frmEstWeight.frmTotalLengthWeight.Form.RecordSource = strSQL3
End Sub
This is working exactly as it should with no errors or anything.
This is within a form correct?
If so, replace the manual values you put in with
REST OF THE QUERY HERE " & Me!Controlname.value & " REST OF THE QUERY HERE
and if you are using something with a control source then just reset the control source value.
me!ControlWithResult.control source = "SELECT tbl2013BOM.fJobID, Sum (tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & me!controlname.value & "));"
For Non-Steel try:
On the VBA for the popup form
me!Combo25.rowsource = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & forms!MAINFORMNAME! &"));

select [combobox value] & "text"

I am trying to build SELECT statement in Access VBA, based on value chosen by user in ComboBox.
Example :
"SELECT [8_SV_RT] FROM DATA WHERE condition = value
I need 8 to be dependent on ComboBox value from form. (8,10,12 ....)
The name of ComboBox is DN, and I created string COL = "_SV_RT"
So far I have :
"SELECT [DN] & '" & COL & "' FROM DATA WHERE condition = value
It returns value 8_SV_RT to ComboBox, which I want to use after SELECT statement, but not as result. I must be missing some syntax or something? Can anyone please advise?
If I understand your question right:
Dim SQL As String
SQL = "SELECT [" & Me.MyComboBox & "_SV_RT] FROM DATA WHERE condition = value"
EDIT:
To use the exact object names from the question (before Siddharth edited it, I over-read that the combobox is named DN) and to take Siddharth's (now deleted) comment into consideration:
Dim SQL As String
Dim COL As String
COL = "_SV_RT"
SQL = "SELECT [" & DN & COL & "] FROM DATA WHERE condition = value"