access vba concatenate single column query into a single line result - vba

I have a new database to help produce documents for order processing.
I have a query set up with only one column of results (Product Codes) determined by the order selected on the main form.
I need to be able to use this information to name my file aka
(Customer) (Product1)+(Product2)+(Product....) (Location)
I have the code to generate the line (Customer) (Product1) (Location) and am trying to get either a concatenate function or a loop function or something to get all the products to line up with a "+" in between each "line".
I have a query (Query1) set up to give me the exact data I need...
SELECT tblREF_Chemical.Abbr
FROM qry_AX_LineItems_DISTINCT INNER JOIN tblREF_Chemical ON
qry_AX_LineItems_DISTINCT.ItemId = tblREF_Chemical.[Item Number]
GROUP BY tblREF_Chemical.Abbr, qry_AX_LineItems_DISTINCT.SALESID,
tblREF_Chemical.[Proper Shipping Name]
HAVING (((qry_AX_LineItems_DISTINCT.SALESID)=[Forms]![frm_SalesOrderEntry]!
[Combo617]) AND ((tblREF_Chemical.[Proper Shipping Name]) Is Not Null));
I have a button set up on my main form to test the data output and then I intend to add the code to my code for DoCmd.Output file name.
So far the only code that has worked is...
Private Sub Command1492_Click()
Dim i As Integer
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim SQL As String
Set db = CurrentDb
SL = [Forms]![frm_SalesOrderEntry]![Combo617]
SQL = "SELECT * FROM ALL_SalesOrderItemsLineDates WHERE
ALL_SalesOrderItemsLineDates.SALESID = '" & SL & "';"
Set rst = db.OpenRecordset(SQL)
For i = 0 To DCount("*", "ALL_SalesOrderItemsLineDates",
"ALL_SalesOrderItemsLineDates.SALESID = '" & [Forms]![frm_SalesOrderEntry]!
[Combo617] & "'") - 1
Debug.Print DLookup("[Abbr]", "[tblREF_Chemical]", "[Item Number]= '" &
rst.Fields("ItemID") & "'")
rst.MoveNext
Next i
rst.Close
End Sub
I can't seem to add additional where statements within this code or use my actual query or the system presents errors at the db.OpenRecordset line of code (Errors 3061 and 3078).
Even ignoring those problems the output is multi-line and I need it to be used in a single string of text for the document name.
UPDATE1:
I am working with the code to use my query directly...
Dim i As Integer
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim SQL As String
Set db = CurrentDb
SL = [Forms]![frm_SalesOrderEntry]![Combo617]
SQL = "SELECT tblREF_Chemical.Abbr "
SQL = SQL & "FROM qry_AX_LineItems_DISTINCT INNER JOIN tblREF_Chemical ON qry_AX_LineItems_DISTINCT.ItemId = tblREF_Chemical.[Item Number] "
SQL = SQL & "GROUP BY tblREF_Chemical.Abbr, qry_AX_LineItems_DISTINCT.SALESID, tblREF_Chemical.[Proper Shipping Name] "
SQL = SQL & "HAVING ((qry_AX_LineItems_DISTINCT.SALESID)='" & SL & "'"
SQL = SQL & "AND ((tblREF_Chemical.[Proper Shipping Name]) Is Not Null)); "
Set rst = db.OpenRecordset(SQL)
Dim s As String
Do While rst(0) Is Not Null
s = s & "+" & rst(0)
rst.MoveNext
Loop
rst.Close
Debug.Print s
Unfortunately I'm now getting a run-time error 3061 - Too few parameters. Expected 1.
I have double checked my spellings and ran the query just to be sure and no matter how many results the query is getting (functioning as expected) I am still getting this error.
UPDATE2:
Through more research I learned that queries can have, for lack of better words, invisible coding. I am updating my code to remove the inner query from my query to simplify the amount of "research" my VBA has to do.
Private Sub Command1492_Click()
Dim i As Integer
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim SQL As String
Set db = CurrentDb
SL = [Forms]![frm_SalesOrderEntry]![Combo617]
SQL = "SELECT tblREF_Chemical.Abbr "
SQL = SQL & "FROM ALL_SalesOrderItemsLineDates INNER JOIN tblREF_Chemical ON ALL_SalesOrderItemsLineDates.ItemId = tblREF_Chemical.[Item Number] "
SQL = SQL & "GROUP BY tblREF_Chemical.Abbr, ALL_SalesOrderItemsLineDates.SALESID, tblREF_Chemical.[Proper Shipping Name]"
SQL = SQL & "HAVING ((ALL_SalesOrderItemsLineDates.SALESID)='" & SL & "'"
SQL = SQL & "AND ((tblREF_Chemical.[Proper Shipping Name]) Is Not Null)); "
Set rst = db.OpenRecordset(SQL)
Dim s As String
Do While rst(0) Is Not Null 'Debug error here!
s = s & "+" & rst(0)
rst.MoveNext
Loop
rst.Close
Debug.Print s
End Sub
Unfortunately I'm still getting a run-time error, but now it is 424 Object required and the debug takes me to the "Do While" line.
I think this is a step forward, but still a little stuck.
Update3:
Since the debug was taking me to the "Do While" line I returned to my functioning code and replaced the loop function with an integer based code.
Thank you #Harassed Dad! Your code was a giant help! Using your idea for a string rather than going straight to a debug.print was genius.
The below replaces my code starting where I was having issues.
Dim s As String
For i = 0 To DCount("*", "ALL_SalesOrderItemsLineDates", "ALL_SalesOrderItemsLineDates.SALESID = '" & SL & "'") - 1
s = s & "+" & rst.Fields("Abbr")
rst.MoveNext
Next i
rst.Close
Debug.Print s
My results are displaying with only one hiccup.
+CHA+DEEA+EEP+MEC+PERC+PM+PROP
There is an extra "+" at the beginning, but I'm sure I can find the solution to this tiny problem.
I hope these notes can help someone in the future. Thank you all for your help!

Private Sub Command1492_Click()
Dim i As Integer
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim SQL As String
Set db = CurrentDb
SL = [Forms]![frm_SalesOrderEntry]![Combo617]
SQL = "SELECT tblREF_Chemical.Abbr "
SQL = SQL & "FROM qry_AX_LineItems_DISTINCT INNER JOIN tblREF_Chemical ON "
SQL = SQL & "qry_AX_LineItems_DISTINCT.ItemId = tblREF_Chemical.[Item Number] "
SQL = SQL & "GROUP BY tblREF_Chemical.Abbr, qry_AX_LineItems_DISTINCT.SALESID, "
SQL = SQL & "tblREF_Chemical.[Proper Shipping Name] "
SQL = SQL & "HAVING (((qry_AX_LineItems_DISTINCT.SALESID)='" & SL & "'" 'edit here
SQL = SQL & "AND ((tblREF_Chemical.[Proper Shipping Name]) Is Not Null)); "
Set rst = db.OpenRecordset(SQL)
Dim s as string
Do While rst(0) is not null
s = s & "+" & rst(0)
rst.MoveNext
Loop
rst.Close
Debug.print s
End Sub

Your main issue is a missing space before the AND in HAVING clause.
For this very reason of readability and maintainability, consider using QueryDefs for parameterized queries (an industry best practice) to run your saved query in VBA for several reasons:
You avoid the need to concatenate or enclose quotes or escape literals by effectively divorcing SQL code from VBA (application layer) code.
MS Access will not allow you to save a query with syntax issues but VBA string queries can have such issues found at runtime.
MS Access's engine compiles and caches saved queries to best execution plan which especially helps for aggregate queries with joins. This is why saved queries are usually more efficient than VBA string queries run on the fly.
SQL (save below as a saved query)
Query now uses table aliases and HAVING conditions are moved to WHERE since no aggregate is being used.
PARAMETERS idparam LONG;
SELECT t.Abbr
FROM qry_AX_LineItems_DISTINCT q
INNER JOIN tblREF_Chemical t ON q.ItemId = t.[Item Number]
WHERE (((q.SALESID) = [idparam])
AND ((t.[Proper Shipping Name]) Is Not Null))
GROUP BY t.Abbr, q.SALESID, t.[Proper Shipping Name];
VBA
Dim db As DAO.Database, qdef AS DAO.QueryDef, rst As DAO.Recordset
Dim SQL As String, s As String
Set db = CurrentDb
' INITIALIZE SAVED QUERY
Set qdef = db.QueryDefs("mySavedQuery")
' BIND PARAMETER
qdef![idparam] = [Forms]![frm_SalesOrderEntry]![Combo617]
' OPEN RECORDSET
Set rst = qdef.OpenRecordset()
Do While rst(0) Is Not Null
s = s & "+" & rst(0)
rst.MoveNext
Loop
rst.Close
Debug.Print s
Set rst = Nothing: Set qdef = Nothing: Set db = Nothing

Related

Where with And Clause SQL, Access-VBA

Hi Everyone, Another Installment of WTF am I missing?
When I run this code I get a missing operator run-time Error, see attached photo.
I can't seem to figure it out. This string is used to open a recordset that will populate a form.
Private Sub BtnUseSelection_Click()
Dim CompSQL As String
CompSQL = "SELECT T1Company.LegalName, T2AddressType.AddressType, T1Addresses.City" & _
" FROM T2AddressType INNER JOIN (T1Addresses INNER JOIN (T1Company INNER JOIN T3Company_Addresses ON T1Company.CompanyID = T3Company_Addresses.CompanyID) ON T1Addresses.AddressID = T3Company_Addresses.AddressID)" & _
" ON T2AddressType.AddressTypeID = T1Addresses.AddressType" & _
" WHERE T1Company.LegalName = " & Me.LstboxCompanies.Column(0) & " And T2AddressType.AddressType = " & Me.LstboxCompanies.Column(1) & " And T1Addresses.City = " & Me.LstboxCompanies.Column(2)
Set db = CurrentDb
Set RSCompany = db.OpenRecordset(CompSQL, dbOpenSnapshot, dbSeeChanges)
Not quite sure what I am missing, any help would be greatly appreciated.
Consider parameterizing query to avoid any need for quote enclosure or string concatenation.
SQL (save below as a saved Access query, more efficient than VBA string query as database engine saves best execution plan)
PARAMETERS [LegalNameParam] Text(255), [AddressTypeParam] Text(255),
[CityParam] Text(255);
SELECT T1Company.LegalName, T2AddressType.AddressType, T1Addresses.City
FROM T2AddressType
INNER JOIN (T1Addresses INNER JOIN (T1Company
INNER JOIN T3Company_Addresses
ON T1Company.CompanyID = T3Company_Addresses.CompanyID)
ON T1Addresses.AddressID = T3Company_Addresses.AddressID)
ON T2AddressType.AddressTypeID = T1Addresses.AddressType
WHERE T1Company.LegalName = [LegalNameParam]
AND T2AddressType.AddressType = [AddressTypeParam]
AND T1Addresses.City = [CityParam]
VBA (call the above query and bind values to named parameters)
Dim db As Database, RSCompany As Recordset, qdef As QueryDef
Dim CompSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("myStoredQuery")
qdef!LegalNameParam = Me.LstboxCompanies.Column(0)
qdef!AddressTypeParam = Me.LstboxCompanies.Column(1)
qdef!CityParam = Me.LstboxCompanies.Column(2)
Set RSCompany = qdef.OpenRecordset(dbOpenSnapshot, dbSeeChanges)
It seems you've missed the ' ' around your string literals.
instead of
... WHERE T1Company.LegalName = " & Me.LstboxCompanies.Column(0) & " ...
use:
... WHERE T1Company.LegalName = '" & Me.LstboxCompanies.Column(0) & "' ...
You also need to escape your strings to avoid corruption of the command (or sql injections). Look here and here for some info.

Access VBA: Cannot combine variable and string in SQL query

I have a list of users (as string variable) and want to use it as the criteria (one user at a time) for my SQL to pick the first item's code. So I put a SQL query as a string to run it later in the code.
I've tried this:
strSQL = "SELECT TOP 1 Item.Code FROM Item WHERE Item.User = '"
strSQL = strSQL & strUserName & "' ORDER BY ID DESC"
If the strUserName = "A-user" for example, I only get this SQL string, according to "Quick Watch...":
SELECT TOP 1 Item.Code FROM Item WHERE Item.User = 'A-user
The part with "' ORDER BY ID DESC" isn't included in the SQL string at all!
And for running the SQL query by using "Set rst = CurrentDb.OpenRecordset(strSQL)", I get this error:
Run-time error '3075':
Syntax error (missing operator) in query expression 'Item.User = "A-user"
How can I fix that?
I don't see how your code triggers that 3075 error. However I would use a parameter query instead. That way you can avoid problems with quoted values in your SQL statement.
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSelect As String
Dim strUserName As String
strUserName = "A-user"
strSelect = "SELECT TOP 1 i.Code FROM [Item] AS i WHERE i.User = [which_user] ORDER BY i.ID DESC"
Set qdf = CurrentDb.CreateQueryDef(vbNullString, strSelect)
qdf.Parameters("which_user").Value = strUserName
Set rs = qdf.OpenRecordset
Access sometimes complains about the use of single-quotes. And also add a semi-colon to the end of the statement. Try changing the code to this (where double-quotes are escaped with an extra double-quote:
strSQL = "SELECT TOP 1 Item.Code FROM Item WHERE Item.User = "
strSQL = strSQL & """" & strUserName & """" & " ORDER BY ID DESC;"

Update Access Query using VBA

I'm trying to update an access query using VBA and changing the Like criteria in the SQL statement, but although I know that SQL code works, when running with VBA it continues to return the same information.
My code is below:
Function FTPCost()
Dim database As DAO.database
Dim query As DAO.QueryDef
Dim strSQL As String
Set database = CurrentDb
Set query = database.QueryDefs("ftp_for_a_part_Query")
strSQL = "SELECT ftp_for_a_part.PART, ftp_for_a_part.STD_TOT, ftp_for_a_part.DATE " & _
"FROM ftp_for_a_part " & _
"WHERE (((ftp_for_a_part.PART) Like '******')) " & _
"ORDER BY ftp_for_a_part.DATE DESC;"
'MsgBox strSQL
query.SQL = strSQL
DoCmd.OpenQuery "ftp_for_a_part_Query"
Set query = Nothing
Set database = Nothing
End Function
Solved my problem. The fact the SQL code was not updating the Query was being caused by the query window being open. I did not understand that for the query to run the Query window must be closed.

Store a sql select statement, ran from VBA, in a numeric variable

I'm working on creating a dynamic pass-through query and in order to do so I first need to query my local db and get an ID.
This ID is what I will put into my pass-through query for my WHERE clause of the query.
My string:
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
I'm then trying to do something akin to:
CorpID (integer) = docmd.runsql (getCorpID)
I realize, however that docmd runsql doesn't work with select statements, or return a value even. What can I use to run my string
getCorpId
as sql and store the result (It will only be one result, every time.. one number) in my variable CorpID
Thank you.
Consider about using Recordset :
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim getCorpID As String
Dim CorpID
Set dbs = CurrentDb
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
Set rsSQL = dbs.OpenRecordset(getCorpID , dbOpenSnapshot)
rsSQL.MoveFirst
CorpID = rsSQL.Fields("corpID")

SQL Error Access 2010 VBA Update Command

I need help figuring out an error in my SQL statement. I have been trying several things, but nothing seems to work?
This is the error message I receive
Run-time error '3075':
Syntax error (missing operator) in query expression '([description] = Manufacturing and Delivery Schedule AND [pr_num] = 83)'.
This is my code:
Private Sub Command6_Click()
' ===================================================
' Receives the selected item in the combo box
' ===================================================
' Open the Database connection
Dim data_base As Database
Set data_base = CurrentDb
' Grab description and pr number from the form
Dim desc As string
dim pr_number as long
desc = Combo4.Value
pr_number = Text8.Value
' Build the query
Dim query As String
query = "UPDATE VDR_Table " & _
"SET [received] = [p1] " & _
"WHERE ([description] = " & desc & _
" AND [pr_num] = " & pr_number & ");"
Dim rec_set As DAO.Recordset
Set rec_set = data_base.OpenRecordset(query)
' Build the QueryDef
Set qd = data_base.CreateQueryDef("")
qd.SQL = query
' Execute query
qd.Parameters("p1").Value = true
qd.Execute
' Close nad null record set
rec_set.close
set rec_set = nothing
' Close the connection to the database
data_base.Close
' Prompt the user success
MsgBox "Item has been received"
End Sub
Thanks in advance for any help!
You need to enclose the description field value you are setting in quotes since it is a string field. It should look like this:
' Build the query
Dim query As String
query = "UPDATE VDR_Table " & _
"SET [received] = [p1] " & _
"WHERE ([description] = '" & desc & _
"' AND [pr_num] = " & pr_number & ");"
Removed the links below since they don't matter in this case.
Also, I would recommend using parameters instead of string concatenations to avoid SQL injections. Here's an example of using parameters with VBA - http://support.microsoft.com/kb/181734 - and here is some reasoning on why to use parameterized sql - http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html.