Error 3075-Run Query after multi select listbox is utilized - vba

have a search form in Access 2010 that filters FYs and Quarters based on certain criteria and opens them in a query. One of the criteria is an unbound multi-select list box, SelectTime (Where a person selects "FY15-Q1 and FY15 Q2, for example. The data are stored in a query, z_Basis_QSReport5_Proposal Details. I keep getting an error 3075. Can someone help me with the code?
Private Sub Command56_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim varItem As Variant
Dim strCriteria As String
Dim strSQL As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("z_Basis_QSReport5_Proposal Details_For_Report")
For Each varItem In Me!SelectTime.ItemsSelected
strCriteria = strCriteria & ",'" & Me!SelectTime.ItemData(varItem) & "'"
Next varItem
If Len(strCriteria) = 0 Then
MsgBox "You did not select anything from the list" _
, vbExclamation, "Nothing to find!"
Exit Sub
End If
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
strSQL = "SELECT * FROM z_Basis_QSReport5_Proposal Details " & _
"WHERE z_Basis_QSReport5_Proposal Details.CriteriaFY IN(" & strCriteria & ");"
qdf.SQL = strSQL
DoCmd.OpenQuery "z_Basis_QSReport5_Proposal Details_For_Report"
Set db = Nothing
Set qdf = Nothing
End Sub

I agree with #LiamH that you need to surround your query names with square brackets.
Also it looks like you're trying to change the SQL of a query on the fly - and then call the query before you've saved the changes
qdf.SQL = strSQL
**qdf.close**
DoCmd.OpenQuery "z_Basis_QSReport5_Proposal Details_For_Report"
That being said I think you should be looking at parameter queries or just opening the SQL directly.

When creating query, table, and field names; it is best practice to avoid spaces. However, there is a solution.
When you use SQL and you have a table name with spaces you need to encapsulate it in square brackets. like so:
"SELECT * FROM [z_Basis_QSReport5_Proposal Details] & _
"WHERE [z_Basis_QSReport5_Proposal Details].CriteriaFY .....
EDIT
Before, I mentioned that you should maybe put square brackets around the query name, but if you look at the example here you will see that spaces are acceptable in this instance.
If we go back to your query, strcriteria is a string and therefore you need to put single quotes around it:
strSQL = "SELECT * FROM [z_Basis_QSReport5_Proposal Details] " & _
"WHERE [z_Basis_QSReport5_Proposal Details].CriteriaFY IN('" & strCriteria & "');"
Also, you will need to close your query before you can run it. So qdf.close is required before the docmd.openquery().

Related

Access VBA run query with values passed from a list box

I have made this form in Access and I am hoping to do the following task.
The list box here contains two columns, and can be multi-selected. I want to use the values second column (the right column) and pass them into a query that I set up for the "test2" button below.
And here is my VBA code for the on-click event for the button.
Private Sub test2_Click()
Dim db As dao.Database
Dim qdef As dao.QueryDef
Dim strSQL As String
Set db = CurrentDb
'Build the IN string by looping through the listbox
For i = 0 To Select_Counties2.ListCount - 1
If Select_Counties2.Selected(i) Then
strIN = strIN & "'" & Select_Counties2.Column(1, i) & "',"
End If
Next i
'Create the WHERE string, and strip off the last comma of the IN string
strWhere = " WHERE County_GEOID in " & "(" & Left(strIN, Len(strIN) - 1) & ")"
strSQL = strSQL & strWhere
Set qdef = db.CreateQueryDef("User query results", strSQL)
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
End Sub
I was getting this error:
Can someone tell me what I did wrong in the code? Thank you!
In this example from microsoft they call application.refreshwindow without explanation.
https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/database-createquerydef-method-dao
What I think is going on is that your code fails because access cannot find the query that was just added to it's collection of queries. Also your generated sql is no longer valid.
So: replace my sql with your own valid sql
Private Sub test2_Click()
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim strSQL As String
strSQL = "PARAMETERS GEOID Number; " 'without valid sql this code doesn't run so
'replace my sql with your own.
strSQL = strSQL & "SELECT GEOID FROM Counties"
Set db = CurrentDb
For i = 0 To Select_Counties2.ListCount - 1
If Select_Counties2.Selected(i) Then
strIN = strIN & Select_Counties2.Column(1, i) & ","
End If
Next i
strWhere = " WHERE County_GEOID in " & "(" & Left(strIN, Len(strIN) - 1) & ")"
strSQL = strSQL & strWhere
Debug.Print strSQL
'now the important bit:
db.CreateQueryDef ("User query results") 'create the query
Application.RefreshDatabaseWindow 'refresh database window so access knows it has a new query.
'query will now be visible in database window. make sure to delete the query between runs
'Access will throw an error otherwise
Set qdef = db.QueryDefs("User query results")
qdef.SQL = strSQL
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
End Sub

Microsoft Access 2016 Summarize and Merge Table with SQL

I have a table that I need to format for use in a manual upload process. The table is thousands of rows so I need to use a repeatable process to quickly fix the way the data is given to me into what it needs to be. I have zero ability to control the way the data comes to me today. But, I have to format it to use it due to a system limitation. My current table is 4 columns, I need to output it as 3 columns. I have to group up by field names: "brand" and "promotion". Field name: "skus" I need to take and merge them into one continuous string by a single "brand" and "promotion" combination.
There are duplicate "promotion" by a given brand since they are created at a product level. But, the system they go into need to be "brand", "promotion", "skus".
Not really sure if I need to use VBA to do some of this inside Access. Or I can do this in two different queries.
You will need to use a bit of VBA to do this. The VBA will need to loop a recordset of data from the table that is filtered on brand and promotion and build up the sku string. Something like this perhaps:
Function fJoinData(strBrand As String, strPromotion As String) As String
On Error GoTo E_Handle
Dim db As DAO.Database
Dim rsData As DAO.Recordset
Dim strSQL As String
Set db = DBEngine(0)(0)
strSQL = "SELECT skus FROM Table1 " _
& " WHERE Brand='" & strBrand & "' " _
& " AND Promotion='" & strPromotion & "';"
Set rsData = db.OpenRecordset(strSQL)
If Not (rsData.BOF And rsData.EOF) Then
Do
fJoinData = fJoinData & ", " & rsData!skus
rsData.MoveNext
Loop Until rsData.EOF
End If
If Left(fJoinData, 2) = ", " Then fJoinData = Mid(fJoinData, 3)
fExit:
On Error Resume Next
rsData.Close
Set rsData = Nothing
Set db = Nothing
Exit Function
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "fJoinData", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume fExit
End Function
Rather than inserting into a table, I would suggest just creating a query which can then be exported:
SELECT DISTINCT
T.Brand,
T.Promotion,
fJoinData(T.Brand,T.Promotion) AS skus
FROM Table1 AS T
Regards,

Update a Table field with current time

Good day all,
I have a unbounded form with a subform (its data source is a table named SaleDetail).
On the Main Form there is a text box for the Sales ID also unbounded.
I have created a button with the following code:
Private Sub btnEndSale_Click()
Dim strPostTime As String
strPostTime = "UPDATE SaleDetail " & _
"SET [TIMEOUT] = Time()" & _
"WHERE SaleDetail.SID = Forms!Sales.Form.sSID"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
End Sub
I am trying to get the current time to update the records in the SalesDetail table once the SID on the Main Form matches the SID in the SalesDetail Table but it is not working, but if I substitute Forms!Sales.Form.sSID with an existing ID (eg 9) it works. Any help will be appreciated.
SetWarnings False suppresses information, so can be an obstacle to trouble-shooting. And it can be totally avoided with a parameter query.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strUpdate As String
strUpdate = "UPDATE SaleDetail SET [TIMEOUT] = Time() " & _
"WHERE SaleDetail.SID = which_SID;"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
With qdf
.Parameters("which_SID").Value = Forms!Sales.Form.sSID.Value
.Execute dbFailOnError
End With
MsgBox db.RecordsAffected & " records updated"
Try this:
strPostTime = "UPDATE SaleDetail " & _
"SET [TIMEOUT] = Time()" & _
"WHERE SaleDetail.SID = " & Forms!Sales.Form.sSID
I think that newbieDBBuilder is not asking about SQL Server query which could use parameters. His code is:
DoCmd.RunSQL strSQL
which is MS Access command and queries Access db.

vba access append multiple tables into one

First off I'm a novice at programming.
Question I have built the code below from many examples off the internet.
The database is named "Code Holder" at this time I have a table "test" and into that table I want append as many tables as there are in the database.
All columns will be the same for all tables
The table names other than "Test" will change
What I have so far is below,
The code runs fine, but I can't seem to get each table to append into the "Test" table, each table comes up blank in the SQL string
Sub append4()
Dim db As Database
Dim tdf As TableDef
Dim rs As Recordset
Set db = currentdb()
Set rs = db.OpenRecordset("test")
For Each tdf In db.TableDefs
StrSQL = "INSERT INTO " & "test" & " " & _
"SELECT * " & _
"FROM " & "rs!tablename" & " ;"
DoCmd.RunSQL StrSQL
Next tdf
Set db = Nothing
End Sub
I want to say that I haven't set rs. correctly but I'm not certain.
Any help would be appreciated.
Thanks
Afternoon, after posting I came across somthing that really helped. Below is the updated VBA code and after testing it works for me.
Thanks Barett, yes I was referencing a table incorrectly, but that's what happens when you stare at somthing for way too long.
Feel free to copy and use if you'd like
'please note there are a few things that one assumes while using this code
'1 all tables column headers are the same
'2 this was used with Access 2010
Sub testeroony2()
Dim db As DAO.Database
Dim tdf As DAO.TableDef
'you can set this database to other databases if you wanted too
Set db = currentdb
For Each tdf In db.TableDefs
' ignore system and temporary tables
'if you want to use it for your own use then you will need to change "test" that is the main table that gets uploaded too
If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "test") Then
'you will need to also change "test" below to the main table you want appended too
StrSQL = "INSERT INTO " & "test" & " " & _
"SELECT * " & _
"FROM " & tdf.Name & " ;"
DoCmd.RunSQL StrSQL
End If
Next
Set tdf = Nothing
Set db = Nothing
End Sub

Syntax for DAO 'Like' Select Query

I'm sorry for bothering you all for what is probably a really simple problem.
I use DAO Select queries fairly frequently but have never needed to filter using 'Like' based on a form field.
The attached code, which should filter based on a combobox (comboRes), throws up a
Syntax error (missing operator) in query expression error.
I'm guessing the error lies in the Like '*' " & strRes & " '*' but I've tried lots of combinations with no joy.
Could someone please straighten out my syntax/code?
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Dim strRes As String
strRes = Me.comboRes
Set qdf = db.QueryDefs("qryInst")
strSQL = "SELECT tblInst.*, tblInst.ResList " & _
"FROM tblInst " & _
"WHERE (((tblInst.ResList) Like '*' " & strRes & " '*'t ));"
qdf.SQL = strSQL
DoCmd.OpenQuery "qryInst"
qdf.Close
db.Close
Set qdf = Nothing
Set db = Nothing
You need to concatenate the string variable to the LIKE clause,
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Dim strRes As String
strRes = Me.comboRes
Set qdf = db.QueryDefs("qryInst")
strSQL = "SELECT tblInst.*, tblInst.ResList " & _
"FROM tblInst " & _
"WHERE tblInst.ResList Like '*" & strRes & "*';"
qdf.SQL = strSQL
DoCmd.OpenQuery "qryInst"
qdf.Close
db.Close
Set qdf = Nothing
Set db = Nothing
So if your strRes is Paul, your SQL will translate to.
SELECT tblInst.*, tblInst.ResList FROM tblInst WHERE tblInst.ResList Like '*Paul*';"
Your SQL needs to be changed somewhat. The like operator takes a string, and the wildcard character depends on the ANSI Query Mode - see here - so you may need to use % instead of *. So to match the contents of strRes anywhere in tblInst.ResList, use the following:
"WHERE tblInst.ResList Like '*" & strRes & "*';"
Note that you are vulnerable to SQL injection when you use this style of code.