Why won't this VB and SQL work? - sql

Private Sub Text46_AfterUpdate()
Dim strSource2 As String
strSource2 = "SELECT [Product Code],[Stock Level],[Description] FROM [products/stock] WHERE [Product Code] LIKE " & "'%" & Me.Text46.Value & "%';"
Me.listSource.RowSource = strSource2
Me.listSource = vbNullString
End Sub
It is supposed to search the database for all products that have a product code matching the value of Text46 in some way, but I really cannot get it to work and I really don't know why. listSource is the listbox that I want the information to appear in.
Thanks in advance,
Bob P

In MS Access, the wildcard is * not %, unless you are working with ADO, or you have changed the ANSI standard in options.
"SELECT [Product Code],[Stock Level],[Description] " _
& "FROM [products/stock] " _
& "WHERE [Product Code] LIKE " & "'*" & Me.Text46.Value & "*';"

Related

Runtime Error 3075 when running SQL query for a search form

I am trying to code a text box search system but am getting Runtime Error 3075.
The recordsource for the form is a SQL statement from a query
that I used. The same SQL statement is in the code below and I added WHERE and OR.
Private Sub btnSearch_Click()
Dim SQL As String
SQL = "SELECT Products.ProdID, categories.CatName, Makes.MakeName, Products.ProdModel, Products.ProdDesc, Suppliers.SuppName, ProdType.TypeName, Colours.ColName, Size.SizeName, Products.DateAdded, Products.ProdBarcode" _
& "FROM Suppliers RIGHT JOIN (categories RIGHT JOIN (ProdType RIGHT JOIN (Makes RIGHT JOIN ((Colours RIGHT JOIN Products ON Colours.ColourID = Products.ColourID) LEFT JOIN [Size] ON Products.SizeID = Size.SizeID) ON Makes.MakeID = Products.ProdMake) ON ProdType.TypeID = Products.ProdTypeID) ON categories.CatID = Products.ProdCategory) ON Suppliers.SuppID = Products.SupplierID" _
& "WHERE (((Products.ProdModel) Like '*" & Me.txtSearch & "*'))" _
& "Or (((Products.ProdBarcode) Like '*" & Me.txtSearch & "*'))" _
& "ORDER BY categories.CatName;"
Me.Form.RecordSource = SQL
End Sub
If anyone can point me in the right direction as to what I am doing wrong will be greatly appreciated.

sql where clause variable

I am using VBA and SQL. My VBA looks like
Dim SystemLookup As String
Dim SqlString As String
If IsNull(Me!SystemLookup) Then
Me!SystemLookup = ""
Else
SystemLookup = Me!SystemLookup
End If
SqlString = "SELECT TblField.*, TblOrigin.SystemID" _
& " FROM TblField INNER JOIN TblOrigin ON TblField.OriginID = TblOrigin.OriginID " _
& " WHERE (((TblOrigin.SystemID) = " & systemlookup )) ""
Me.RecordSource = SqlString
End Sub
I have my bracketing on the where clause is wrong but I am not sure how to fix. Any sugguestions (Systemlookup is a variable that is being passed from a form)
You need to put the brackets inside the string, not besides the variable.
Try this:
SqlString = "SELECT TblField.*, TblOrigin.SystemID" _
& " FROM TblField INNER JOIN TblOrigin ON TblField.OriginID = TblOrigin.OriginID " _
& " WHERE (((TblOrigin.SystemID) = " & systemlookup & ")) "
You are missing an ampersand and a double quote and have an extra opening bracket. The brackets are not needed in this simple query.
SqlString = "SELECT TblField.*, TblOrigin.SystemID" _
& " FROM TblField INNER JOIN TblOrigin ON TblField.OriginID = TblOrigin.OriginID " _
& " WHERE TblOrigin.SystemID = " & systemlookup & ";"
You would bracket WHERE clauses when you need to group conditions.
For example if you wanted to know if a product was shipped between two dates or if the product wasn't shipped then you would bracket it.
All three of these examples are valid:
WHERE ([Shipped Date]>=#10/28/2017# AND [Shipped Date]<=#10/30/2017#) OR [Shipped Date] is Null
WHERE ([Shipped Date]>=#10/28/2017# AND [Shipped Date]<=#10/30/2017#) OR ([Shipped Date] is Null)
WHERE (([Shipped Date]>=#10/28/2017# AND [Shipped Date]<=#10/30/2017#) OR ([Shipped Date] is Null))

MS ACCESS - Error runtime 3141 SQL in VBA

I'm getting error in ms access while trying change subform recordsource based on combo box
The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.
here my code
Private Sub Text4_AfterUpdate()
If (Me.Text4.Value = "(ALL)") Then
filterORIGIN_COD = "SELECT SUMMARY.DEST_CITY, SUMMARY.DESTINATION, Count(SUMMARY.CNOTE_NO) AS CountOfCNOTE_NO1" & _
"FROM SUMMARY" & _
"WHERE (((SUMMARY.ORIGIN_CODE) Like " & "'" * "'" & ")))" & _
"GROUP BY SUMMARY.DEST_CITY, SUMMARY.DESTINATION, SUMMARY.TGL_DATA, SUMMARY.ORIGIN_CODE, SUMMARY.ORIGIN, SUMMARY.DEST_CODE;"
Else
filterORIGIN_COD = "SELECT SUMMARY.DEST_CITY, SUMMARY.DESTINATION, Count(SUMMARY.CNOTE_NO) AS CountOfCNOTE_NO1" & _
"FROM SUMMARY" & _
"WHERE (((SUMMARY.ORIGIN_CODE)=" & """Me![Text4]""" & ")))" & _
"GROUP BY SUMMARY.DEST_CITY, SUMMARY.DESTINATION, SUMMARY.TGL_DATA, SUMMARY.ORIGIN_CODE, SUMMARY.ORIGIN, SUMMARY.DEST_CODE;"
End If
Me![OUTBOUND_DETAIL].Form.RecordSource = filterORIGIN_COD
Me![OUTBOUND_DETAIL].Requery
End Sub
ADDITIONAL
actually I'm trying to filter subform (query record source), can someone show me better ways to do that? :)
If trying to filter subform in a trigger event, simply use DoCmd.ApplyFilter or DoCmd.SetFilter (for Access 2010+) methods which are also available in macros:
Private Sub Text4_AfterUpdate()
DoCmd.ApplyFilter , "[SUMMARY.ORIGIN_CODE]='" & Me![Text4] & "'"
End Sub

VBA string length problem

I have an Access application where everytime a user enters the application, it makes a temp table for that user called 'their windows login name'_Temp. In one of my reports I need to query using that table, and I can't just make a query and set it as the recourdsource of the report, since the name of the table is always different.
What I tried then was to programatically set the recordset of the report by running the query and setting the form's recordset as the query's recordset. When I tried this, it kept giving me an error about the query.
I tried to debug, and I found that the string variable isn't able to contain the whole query at once. When I ran it with break points and added a watch for the string variable, it shows me that it cuts off the query somewhere in the middle.
I've experienced this problem before, but that was with an UPDATE query. Then, I just split it into two queries and ran both of them separately. This one is a SELECT query, and there's no way I can split it. Please help!
Thank you
Heres what I've tried doing:
ReturnUserName is a function in a module that returns just the login id of the user
Private Sub Report_Open(Cancel As Integer)
Dim strQuery As String
Dim user As String
user = ReturnUserName
strQuery = "SELECT " & user & "_Temp.EmpNumber, [FName] & ' ' & [LName] AS [Employee Name], " & _
"CourseName, DateCompleted, tblEmp_SuperAdmin.[Cost Centre] " & _
"FROM (tblCourse INNER JOIN (" & user & "_Temp INNER JOIN tblEmpCourses ON " & _
user & "_Temp.EmpNumber = EmpNo) ON tblCourse.CourseID = tblEmpCourses.CourseID) " & _
"INNER JOIN tblEmp_SuperAdmin ON " & user & "_Temp.EmpNumber = tblEmp_SuperAdmin.EmpNumber" & _
"WHERE (((" & user & "_Temp.EmpNumber) = [Forms]![Reports]![txtEmpID].[Text])) " & _
"ORDER BY CourseName;"
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim rsCmd As ADODB.Command
Set rsCmd = New ADODB.Command
rsCmd.ActiveConnection = CurrentProject.Connection
rsCmd.CommandText = strQuery
rs.Open rsCmd
Me.Recordset = rs
rs.Close
End Sub
This what strQuery contains when I add a breakpoint on rsCmd.CommandText = strQuery:
SELECT myusername_Temp.EmpNumber, [FName]
& ' ' & [LName] AS [Employee Name],
CourseName, DateCompleted,
tblEmp_SuperAdmin.[Cost Centre] FROM
(tblCourse INNER JOIN (myusername_Temp
INNER JOIN tblEmpCourses ON
myusername_Temp.EmpNumber = EmpNo) ON
tblCourse.CourseID=
(It's all one line, but I've written it like this because the underscores italicize the text)
And the error I get says Run Time Error: Join not Supported.
Not quite what I was hoping for, but guessing, for:
strQuery = "long query goes here"
Try:
strQuery = "some long query goes here "
strQuery = strQuery & "more query goes here "
BASED ON NEW INFORMATION:
strQuery = "SELECT " & user & "_Temp.EmpNumber, [FName] & ' ' & [LName] AS [Employee Name], " & _
"CourseName, DateCompleted, tblEmp_SuperAdmin.[Cost Centre] " & _
"FROM (tblCourse " & _
"INNER JOIN tblEmpCourses ON tblCourse.CourseID = tblEmpCourses.CourseID) " & _
"INNER JOIN (Temp INNER JOIN tblEmp_SuperAdmin " & _
"ON Temp.EmpNumber = tblEmp_SuperAdmin.EmpNumber) " & _
"ON Temp.EmpNumber = tblEmpCourses.EmpNo " & _
"WHERE " & user & "_Temp.EmpNumber = " & [Forms]![Reports]![txtEmpID] & _
" ORDER BY CourseName;"
Note that in VBA:
& [Forms]![Reports]![txtEmpID].[Text] &
That is, the reference to the form must go outside the quotes so you get the value.
NEW INFORMATION #2
Your best bet would be to add these tables to the Access query design window and create the joins that you want, then switch to SQL view and use the string generated for you. I do not believe that the string is too long, only that the SQL is incorrect. The SQL I posted above should work, but it may not be what you want.
You can programmatically create a querydef that fits the user. So, when your report is called, you
Delete LoginName_Query_Temp (CurrentDb.QueryDefs.Delete), if it already exists.
Create the querydef (CurrentDB.CreateQueryDef), using LoginName_Temp as the table name.
Set the RecordSource of your Report to LoginName_Query_Temp.
Open the report.
I don't see what purpose the table myusername_Temp serves here. Is that where the name fields are? If so, avoid the join entirely:
Dim lngEmpNumber As Long
Dim strName As String
Dim strSQL As String
lngEmpNumber = Forms!Reports!txtEmpID
strName = DLookup("[FName] & ' ' & [LName]", "myusername_Temp", "EmpNumber=" & lngEmpNumber
strSQL = "SELECT " & Chr(34) & strName & Chr(34) & " AS [Employee Name], " & _
"CourseName, DateCompleted, tblEmp_SuperAdmin.[Cost Centre] " & _
"FROM tblCourse " & _
"INNER JOIN tblEmpCourses " & _
"ON tblCourse.CourseID = tblEmpCourses.CourseID) " & _
"INNER JOIN tblEmp_SuperAdmin " & _
"ON tblEmp_SuperAdmin.EmpNumber = tblEmpCourses.EmpNo " & _
"WHERE tblEmp_SuperAdmin.EmpNumber = " & lngEmpNumber & _
" ORDER BY CourseName;"
Now, the parentheses may need to be changed in the join (I always do my equi-joins in the Access QBE and let it take care of the getting the order and parens correct!), and my assumptions about the purpose of the temp table may be wrong, but I don't see it being used for anything other than as an intermediate link between tables, so I guessed it must be there to provide the name fields.
If that's wrong, then I'm at a loss as to why the temp table needs to be there.
Also, in your second post you referred to the control on the form as:
Forms!Reports!txtEmpID.Text
...the .Text property of Access controls is accessible only when the control has the focus. You could use the .Value property, but since that's the default property of Access controls, you should just stop after the name of the control:
Forms!Reports!txtEmpID
...you'll see this is how I did it in my suggested code.
I find the idea of your name-based temp table to be highly problematic to begin with. Temp tables don't belong in a front end, and it's not clear to me that it is actually a temp table. If it's temp data, put it in a shared table and key the record(s) to the username. Then you don't have to worry about constructing the table name on the fly.

Simple SQL query in Access fails with a missing semicolon error

So, I'm learning Access 2007, Visual Basic, and SQL at the same time. Not ideal.
I have this code attached to a button in a standard wizard-generated interface. I'm trying to copy a line from tblA to tblB. Every time the code is executed I get the message, "Run-time error '3137' Missing semicolon (;) at end of SQL statement."
I'm guessing that it's expecting the SQL statement to terminate earlier, before the WHERE? But without the WHERE, how would I attach the add to a particular line ID?
Private Sub buttonAdd_Click()
Dim strSQL As String
strSQL = "INSERT INTO [tblB]" & _
"VALUES (ID, [Name], [Some value], [Some other value])" & _
"SELECT * FROM tblA" & _
"WHERE ID = '" & Me.ID & "' " & _
";"
DoCmd.RunSQL strSQL
End Sub
Syntax is wrong, you need to remove the "VALUES" keyword.
This is assuming that ID, [Name], [Some value] and [Some other value] are column names of tblB (some hesitation on my part with the last two names having "value").
The VALUES() SQL syntax is used to provide immediate values, but since you're getting the values from tblA, the query should look like:
strSQL = "INSERT INTO [tblB] " & _
"(ID, [Name], [Some value], [Some other value]) " & _
"SELECT * FROM tblA " & _
"WHERE ID = '" & Me.ID & "' " & _
";"
Edit: I also added spaces between tokens. Good catch Nick D, thank for noticing this !
You have put the field names in the values clause instead of after the table name, and there is a space missing between tbla and where. Both the value clause followed by select and the missing space could cause the error message by themselves.
strSQL = "INSERT INTO [tblB] (ID, [Name], [Some value], [Some other value])" & _
"SELECT * FROM tblA " & _
"WHERE ID = '" & Me.ID & "'"
The semicolon at the end is not requiered nowadays. You only need it for separating queries if you run more than one query at a time.
Also, if the ID field is numerical, you should not have apostrophes around the value:
strSQL = "INSERT INTO [tblB] (ID, [Name], [Some value], [Some other value])" & _
"SELECT * FROM tblA " & _
"WHERE ID = " & Me.ID
mjv is correct. You must remove the VALUES keyword and also you should put spaces between keywords, ie:
"SELECT * FROM tblA" & _
"WHERE ID = '" & Me.ID & "' " & _
the above will be joined as "...FROM tblAWHERE ID..."