Access VBA RunSQL Error - sql

I'm trying to insert into a table the top x records from a query data-set. However I keep getting the run-time error '3061' Too few parameters. Expected 1. I've tried a few things but it doesn't make any difference.
Private Sub UpdateGA_Click()
Dim dbs As DAO.Database
Dim strSQL As String
Dim rounds As Integer
Dim playerid As Long
Set dbs = CurrentDb
rounds = Me.NoOfScores.Value
playerid = Me.lngPlayerID.Value
strSQL = "INSERT INTO [tbl_TopRounds] ( [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate]) " & _
" SELECT TOP " & Me.NoOfScores.Value & " [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate] FROM qry_LastRounds" & _
" WHERE [lngPlayerID] = " & Me.lngPlayerID.Value & _
" ORDER BY [dblPlayedTo], [dteRoundDate] DESC;"
dbs.Execute strSQL
End Sub
I'm expecting that x (based on a form parameter) records will be written to the tbl_TopRounds.
VB Error on executing
Any help would be appreciated.

Normally this error means that you made a mistake in field name. Set breakpoint on last command, run the sub, open immediate window and type ?strSQL. Copy received SQL text and try to run it in query builder, it will show column name which doesn't exist in the table. The error may be in the query qry_LastRounds, check it first by opening

Related

SQL statement returning "could not find file" while executing

In my code, I am trying to use an input box to hold a user inputted value as a string, then use SQL to then update a field based on that.
My code is:
Dim strinput
Dim strsql
Call CreateRevisions
strinput = InputBox(prompt:="Name of revision")
If Not IsNull(strinput) Then
'DoCmd.SetWarnings False
strsql = " UPDATE tblJobDetails.RevisionName"
strsql = strsql & " SET tblJobDetails.RevisionName = '" & strinput & "'"
strsql = strsql & " WHERE (((tblJobDetails.JobID)=[Forms]![JobQuote]![JobID]));"
'DoCmd.RunSQL strsql
CurrentDb.Execute strsql
'docmd.setwarnings true
End If
End Sub
When it runs, I get the prompt that fields are about to be updated, then the input box appears and allows me to enter something. I checked the value of strinput and it is holding the value correctly, but when I try to actually execute the SQL statement I can an interesting error I haven't run into before.
The error is :
Run-time error '3024':
Could not find file 'C\....
I have run various statements like this before with no problem. This is the first time I have tried using the input box however. What is causing that error?
I have tried changing it to docmd as well as adding in debug.print, but it still results in the same error.

access vba concatenate single column query into a single line result

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

MS Access: Why am I getting an "Invalid use of property" error?

I'm getting the error in the title when using this code:
Private Sub Command12_Click()
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
Dim query As QueryDef
Dim sql As String
item_entered = Me.Text314.Value
sql = "Update tbl_FilmZipInfo Set qty_per_unit = Me.Text317 WHERE [item] = item_entered ;"
query = CurrentDb.CreateQueryDef("UpdateFilmZip", sql)
query.Execute
End Sub
After I run the Sub, the "Private Sub Command12_Click()" line gets highlighted in yellow and the "query =" gets highlighted in blue (the same blue highlighting that a human does when copying something). Anyone know why I am getting this error? The goal here is to update a specific record in a table.
You have to use the Set keyword when assigning object variables:
Set query = CurrentDb.CreateQueryDef("UpdateFilmZip", sql)
You must concatenate correctly:
sql = "Update tbl_FilmZipInfo Set qty_per_unit = " & Me!Text317.Value & " WHERE [item] = '" & item_entered & "';"
Leave out the last quotes if item_entered is numeric.

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.

Getting Error in vba and cannot figure it out

Trying to get this code to work when hitting a button but im getting this erorr
"A problem occurred while Microsoft Accces was communicating with the OLE server or Acitve X Control."
here is the code
enter code here
Private Sub Command36_Click()
Dim months2, years2, countyID2 As Integer
Dim dr As SqlDataReader
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
Dim SQL
months2 = txtMonths.Value
years2 = txtYears.Value
countyID2 = txtCountyID.Value
Set rs = dbs.OpenRecordset(SQL)
DoCmd.RunSQL "select * from Rule where ChangedFlag = 1 and Years = " + years2 + " and Months = " + months2 + " and CountyID = " + countyID2 + ""
If IsNull(rs) Then MsgBox "Hearing dates are already assigned! Please choose another county, year, or month!"
Else
DoCmd.RunSQL "insert into Rule values (Years, Months, CountyID) Values (years2, months2, countyID2)"
End Sub
DoCmd.RunSQL "select * from Rule where ChangedFlag = 1 and Years = " + _
years2 + " and Months = " + months2 + " and CountyID = " + countyID2 + ""
DoCmd.RunSQL "insert into Rule values (Years, Months, CountyID) Values " & _
" (years2, months2, countyID2)"
In your second SQL statement you're trying to insert literal values "years2", "months2" and "countyID2".
Compare that with your first statement...
GD Jordan,
Your error indicates that you do not get a connection to the database. Which would make sense as you have not indicated where, or to what object, the connection should be made.
In your code you have declared SQL and subsequently use it in your OpenRecordSet(SQL) statement, yet the variable SQL is not defined (i.e. it is declared but does not contain any value or information with which to execute the OpenRecordSet() method)
Please see: https://msdn.microsoft.com/en-us/library/office/ff820966.aspx
For more information on the appropriate use of the OpenRecordSet() method.
Once you have checked that you indeed get the connection (using debugger in VB editor for example) you can then determine how you want your code to interact with the rs object.
By the way there is more wrong with your code, but let's focus on getting the connections first...
Good luck !