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 !
Related
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
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
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.
I am building a MS Access database and I cannot find a solution to my issue anywhere. All I want to do is trigger an update to my table using SQL code upon clicking a button, however, each time I try to run this code I get the error: "Run time error 3061, Too few parameters. Expected 1". The naming of all the tables and fields I call in my SQL code is correct. I copy/pasted the SQL string from my debug print into a query builder and it worked without issue. My code is:
Private Sub cmdAddRev_Click()
Dim compNum As String
Dim docPath As String
Dim filePath As String
Dim lastRev As Integer
Dim updateRev As Integer
Dim sqlStr As String
compNum = Me.cboRevSelection.Value
docPath = Me.tboRevDocLoc.Value
filePath = Me.tboRevFileLoc.Value
lastRev = DLookup("numLastRev", "tblComponents", "num = [Forms]![frmRevisor]![cboRevSelection]")
updateRev = lastRev + 1
sqlStr = " UPDATE tblComponents "
sqlStr = sqlStr & " SET numLastRev = " & updateRev
sqlStr = sqlStr & " WHERE num = [Forms]![frmRevisor]![cboRevSelection] "
CurrentDb.Execute (sqlStr) 'this line is flagged when the error happens
Debug.Print sqlStr
End Sub
Change this line:
sqlStr = sqlStr & " WHERE num = [Forms]![frmRevisor]![cboRevSelection] "
to this:
sqlStr = sqlStr & " WHERE num = '" & [Forms]![frmRevisor]![cboRevSelection] & "'"
SQL from VBA, doesn't like parameters. Always use your references outside of the quotes, so that the query going to the execute already has values in it. (although using a parametized query would be better still...)
You can't reference a form when executing SQL via VBA. There are several options. Set a tempvar to the desired value and reference the tempvar in the SQL or create a public function referencing the form and use the function in the SQL
Public Function RevSelection()
RevSelection = [Forms]![frmRevisor]![cboRevSelection]
End Function
Then use
sqlStr = sqlStr & " WHERE num = RevSelection()"
or, the simplest, reference it as a value.
sqlStr = sqlStr & " WHERE num =" & [Forms]![frmRevisor]![cboRevSelection]
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.