Set Text Box equal to Query - sql

I have a query in an Access Db that counts the number of observations that meet a certain criteria as defined by two comboboxes. The query works fine, and I can get the result of the query to display and update live with the comboboxes using subforms, but the subforms are an extremely ugly way to represent a single number.
I would like to use a textbox to display that single number from the query instead of a subreport. I've tried inputting the SQL of the query into the Control Source and the Default Value, but no success.
After reading through the forum it appears I can write a function and then set my control source equal to that function.
Here is my VBA:
Public Function AdultCount()
Dim rs As Recordset
Set rs=CurrentDb.OpenRecordset("Select Count([name]) as [# Vars] from Masterdb where ((masterdb.year=[forms]![Masterform]![NavigationSubform].[form]![year]) and (masterdb.recipient=[forms]![Masterform]![NavigationSubform].[form]![recipient]) and (masterdb.group="adult"))")
AdultVar=rs!Result
rs.Close
Set rs=Nothing
End Function
I get "compile error: Expected:list separator or )"
and it highlights "adult" at the end of my SQL query.
I don't know why this isn't working. Does anyone know why I'm getting this error, and tell me if I'm even doing the right thing to get what I want?
edit:
I now have
Dim strSQL AS String
strSQL = "Select Count([name]) as [# Vars] from Masterdb where [year] = " & Me.NavigationSubform.year.value & " and [recipient] = " & Me.NavigationSubform.recipient.value & " and [group]='adult'"
Set rs=CurrentDb.OpenRecordset(strSQL)
AdultVar=rs![# Vars].Value
rs.Close
Set rs=Nothing
End Function
But the textbox reads "#Name?"
Any ideas?

The double quotes for "adult" are throwing the error because you're closing and reopening a string without telling VB what to do with adult"))"). SQL needs single quotes anyway, so change it to 'adult' and the error will go away.

A second option is to build your string first, like so:
Dim strSQL AS String
strSQL = "Select Count([name]) as [# Vars] from Masterdb where [year] = " & Me.NavigationSubform.year.value & " and [recipient] = " & Me.NavigationSubform.recipient.value & " and [group]='adult'"
Set rs=CurrentDb.OpenRecordset(strSQL)
If you're not familiar with using the Me keyword, do a bit of reading up as it will shorten your code and save you time.

Related

Return Query Value Using VBA function in Access

I'm currently working on a project and I've been having trouble trying to get a function that is able to return the value of a query, which I do need in order to display it on a textbox.
The current code is like this:
Public Function rubrieknaamSQL() As String
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT T_Train.trainPlate, T_Category.categoryName FROM T_Category INNER JOIN T_Train ON T_Category.id = T_Train.category_id WHERE (((T_Train.trainPlate)=[Forms]![F_Comboio]![Combo_Search_Comboio]));"
Set rst = CurrentDb.OpenRecordset(strSQL)
rubrieknaamSQL = rst!categoryName
rst.Close
End Function
I should say that the code is copied from other publisher and I do not own its rights. However, it still won't work when I try to run it and the error displayed goes like this:
Run-Time Error 3061 : Too few parameters. Expected 1
and it happens in Set rst command.
For a SELECT query to set a recordset object, concatenate variable:
" ... WHERE T_Train.trainPlate=" & [Forms]![F_Comboio]![Combo_Search_Comboio]
If trainPlate is a text field, need apostrophe delimiters (date/time field needs # delimiter):
" ... WHERE T_Train.trainPlate='" & [Forms]![F_Comboio]![Combo_Search_Comboio] & "'"
For more info about parameters in Access SQL constructed in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?
There are ways to pull this single value without VBA.
make combobox RowSource an SQL that joins tables and textbox simply references combobox column by its index - index is 0 based so if categoryName field is in third column, its index is 2: =[Combo_Search_Comboio].Column(2)
include T_Category in form RecordSource and bind textbox to categoryName - set as Locked Yes and TabStop No
build a query object that joins tables without filter criteria and use DLookup() expression in textbox
=DLookup("categoryName", "queryname", "trainPlate='" & [Combo_Search_Comboio] & "'")

ms-access vba-access Dlookup error 3464 cant get code to run

I am trying to make sure that a value from one single record table does not excist in another table.
I have one table with a single record called Settings.
I have a second table holding Unique ID's (jobnumber) called Courier.
I am trying to make sure that the value Quotenumber in the table Settings does not excist in Jobnumber in the table Courier before moving on with the code.
to test this I created the following.
Private Sub Knop0_Click()
Dim db As Database
Dim Mytable As Recordset
Set db = CurrentDb()
Set Mytable = db.OpenRecordset("settings")
Set Quote = Mytable!Quotenumber
If DLookup("[jobnumber]", "[courier]", "[jobnumber]= " & Quote) > 0 Then MsgBox "its in there" Else MsgBox "its not in there"
End Sub
when running the code i get Error 3464.
I found the problem is with "Quote" and tried to use a couple of Dim to fix this but I just cant get it to work.
Mind my experience with VBA is low and for every line of code i write i have to do extensive research. I have verry little knowledge of how DIM exactly works.
Try with:
If IsNull(DLookup("[jobnumber]", "[courier]", "[jobnumber]= " & Quote & "") Then
MsgBox "its not in there"
Else
MsgBox "its in there"
End If
If Jobnumber is text, then:
If IsNull(DLookup("[jobnumber]", "[courier]", "[jobnumber]= '" & Quote & "'") Then

Execute a SQL statement inside VBA Code

I am attempting to execute a SQL query inside of VBA Code. The query works in MS Access and asks the user to input a value for Customer_Name and Part_Number
What I have done is written the VBA Code in outlook so we can run the macro to execute the query from Outlook. The code I have currently works until the very bottom line on the DoCmd.RunSQL portion. I think I have this syntax incorrect. I need to tell it to run the string of SQL listed above:
Public Sub AppendAllTables()
Part_Number = InputBox("Enter Part Number")
Customer_Name = InputBox("Enter Customer Name")
Dim strsqlQuery As String
Dim Y As String
Y = "YES, Exact Match"
Dim P As String
P = "Possible Match - Base 6"
Dim X As String
X = "*"
strsqlQuery = "SELECT Append_All_Tables.Customer,
Append_All_Tables.CustomerCode, Append_All_Tables.PartNumber,
Append_All_Tables.Description, Append_All_Tables.Vehicle, SWITCH" &
Customer_Name & " = Append_All_Tables.PartNumber, " & Y & ", LEFT(" &
Part_Number & ",12) = LEFT(Append_All_Tables.PartNumber,12)," & Y & ",
LEFT(" & Part_Number & ",6) = LEFT(Append_All_Tables.PartNumber,6)," & P
& ") AS Interchangeability FROM Append_All_Tables WHERE" & Customer_Name
& "Like " & X & Customer_Name & X & "AND
LEFT(Append_All_Tables.PartNumber,6) = LEFT(" & Part_Number & ",6);"
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase "path.accdb"
appAccess.DoCmd.RunSQL "strsqlQuery"
End Sub
Please note, the path has been changed for privacy. The SQL code already works in Access. I am only needing the last line to be evaluated.
If you want to have a datasheet form view show these records you can use
DoCmd.OpenForm
First create a query with the data you want to see, then bind that to your form using the Record Source property, then when you call DoCmd.OpenForm pass in the filter you want.
I'm not following what you're trying to do with SWITCH in your query (is that supposed to be the switch() function? it has no parentheses). But you'll need to adjust that to join to use a Where statement instead.
I agree with a couple of the above posts.
You need to do a Debug.Print of the strsqlQuery variable BEFORE YOU DO ANYTHING! Then evaluate that statement. Does it look right? As Matt says, it doesn't look like you have line continuations, which would make your SQL statement incomplete (and thus, the computer doesn't think its a query at all).
My personal preference is to define the SQL like you have, then create the actual query using that SQL (create query def), and then call that query, because it will now be an actual object in the database. The QUERY can show up as a datasheet without any form requirement, but a pure SQL Statement cannot.
Michael
Remove the quotes.
appAccess.DoCmd.RunSQL "strsqlQuery" to appAccess.DoCmd.RunSQL strsqlQuery

SQL statement in VBA

I am trying to run the following SQL statement in ACCESS 2013 VBA but am getting errors due to wrong formatting (in this case I get "Semicolon (;) missing from end of statement"). Could anybody tell me what I am doing wrong in the code below please?
Dim dbs As dao.Database
Set dbs = CurrentDb()
dbs.Execute "INSERT INTO TEMP2 ([Study_Date], [Created_By], [Part_Number],
[Upper_Tolerance], [Lower_Tolerance], [ID21_Number]) VALUES ([Study_Date],
[Created_By], [Part_Number], [Upper_Tolerance], [Lower_Tolerance], [ID21_Number])
FROM RAC_DATA_ENTRY
WHERE [RAC_CAP_VALS] = '" & Me.[RAC_CAP_VALS] & "'"
Don't use VALUES when you're pulling data from one table to INSERT into another. Use SELECT instead.
This example uses just two of your fields. Add in the others you need.
Dim strInsert As String
strInsert = "INSERT INTO TEMP2 ([Study_Date], [Created_By])" & _
" SELECT [Study_Date], [Created_By] FROM RAC_DATA_ENTRY" & _
" WHERE [RAC_CAP_VALS] = '" & Me.[RAC_CAP_VALS].Value & "';"
Debug.Print strInsert '<- view this in Immediate window; Ctrl+g will take you there
dbs.Execute strInsert, dbFailOnError
Notes:
A semicolon at the end of the statement is optional. Access will consider the statement valid with or without it.
Value is not actually required following Me.[RAC_CAP_VALS], since it's the default property. I prefer to make it explicit.
dbFailOnError gives you better information about failed inserts. Without it, a problem such as a primary key violation would fail silently.
Debug.Print strInsert allows you to inspect the statement you built and are asking the db engine to execute. If there is a problem, you can copy the statement text from the Immediate window and paste it into SQL View of a new Access query for testing.

count the number of rows in sql query result using access vba

I am trying to count the number of rows in sql query result using access 2007 vba.
What I have is a text box named AGN when a user put value on it check for this value then it bring back MsgBox if the the value is already inserted. What I try to do is :
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT agencies.[agency no] FROM agencies WHERE agencies.[agency no]= " &Me.AGN.Text
Set rs = db.OpenRecordset(strSQL)
If rs.Fields.Count > 1 Then
MsgBox "this value is already here "
End If
Set rs = Nothing
When I insert any value on the textbox I got run time error 3061 (too few parameters)
The "too few parameters" error message generally means there is something in your SQL statement which Access doesn't recognize as a field, table, function or SQL keyword. In this case, it could happen if [agency no] is text rather than numeric data type. If that is the case, enclose the value of AGN with quotes when you build the SQL statement. (Or you could use a parameter query to avoid the need to quote the text value.)
strSQL = "SELECT a.[agency no] FROM agencies AS a" & vbCrLf & _
"WHERE a.[agency no]= '" & Me.AGN.Value & "'"
Debug.Print strSQL
In case of trouble, go to the Immediate window and copy the output from Debug.Print. Then you can create a new query in the Access query designer, switch to SQL View and paste in the statement text for testing.
Once your SELECT is working, you can check whether or not the recordset is empty. When it is empty both its BOF and EOF properties are true. So to detect when it is not empty, check for Not (BOF And EOF) ...
With rs
If Not (.BOF And .EOF) Then
MsgBox "this value is already here "
End If
End With
However you don't actually need to open a recordset to determine whether a matching row exists. You can check the value returned by a DCount expression.
Dim lngRows As Long
lngRows = DCount("*", "agencies", "[agency no]='" & Me.AGN.Value & "'")
If lngRows > 0 Then
MsgBox "this value is already here "
End If
Notes:
I used AGN.Value instead of AGN.Text because the .Text property is only accessible when the control has focus. But I don't know where you're using that checking code, so unsure which is the proper choice for you.
Notice the similarities between the SELECT query and the DCount options. It's often easy to translate between the two.