Passing a variable into SQL With VBA/Access - ms-access

I have a Case Statement that reassigns a string variable [Conveyor_ID] depending on the case. Then I pass this variable via a SQL statement into a openrecordset method.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Const DbLoc As String = "database location"
Set db = OpenDatabase(DbLoc)
Set rs = db.OpenRecordset("SELECT Width FROM $[Conveyor_ID]%")
I am getting a error stating " invalid bracketing of name "$Conveyor_ID]%" "
I have tried a few variations, but I don't quite seem to know how to pass a variable into a SQL statement. Can anyone point me in the right direction?
Thanks
(Brand new, Mech Eng. trying to make some useful programs!)

Can we see how this Conveyor_ID is being defined? It might make it easier to answer the question.
Assuming your [Conveyor_ID] is defined as Conveyor_ID in the VBA function, why not try
Set rs = db.OpenRecordSet("SELECT Width FROM " & Conveyor_ID)

MS Access VBA concatenates strings with &.
In your recordset, the SQL string needs to be changed to:
Set rs = db.OpenRecordset("SELECT Width FROM " & Conveyor_ID & ";")
Edit: You also might need the semicolon at the end of the SQL. Added semicolon.
Edit2: Since you clarified that Conveyor_ID is a string variable, then you will need to add single quotes around it. My previous answer works for numbers. Dates would have # in place of single quotes.
And as Erik von Asmuth mentioned below, it looks like semicolons aren't required in Access in the VBA window. It's a personal preference.
Your code for the recordset should now look like this with the string:
without semicolon:
Set rs = db.OpenRecordset("SELECT Width FROM '" & Conveyor_ID & "'")
with semicolon:
Set rs = db.OpenRecordset("SELECT Width FROM '" & Conveyor_ID & "';")
I just noticed:
1. The brackets - you can't use them in VBA on a variable or argument. You would use them in SQL, for example, if your table name or field name had a space in it (see below code for example table name with space), but it's bad practice
2. You are missing your table name and WHERE clause in your SQL string (if this is your full SQL string and not pseudocode)
Set rs = db.OpenRecordset("SELECT Width FROM [table Name] WHERE fieldName = '" & Conveyor_ID & "'")

Related

Object variable error

I've got a subform (RegistrationFsub) based on table Registration. It's purpose is to create a one-to-many relationship between a person and the year(s) they have enrolled in the group.
When a mom enrolls in a new year, I have a command button that is supposed to add a new line to the table Registration with MomID (from the parent form: MomsFsub) and the start date of the current enrollment year (YearStart, from table Year). Since the current enrollment period is represented by the latest date, I want to use the Max() command to retrieve it from YearT. I tried the following code:
Dim db As DAO.Database
Dim sqlSTR As String
Dim IDvar As String
'new code added since question posted
Set db = CurrentDb
Call MsgBox (Max(YearT!YearStart), vbOKonly)
'MsgBox checks value returned for Max(YearStart)
'end new code
IDvar = CStr(MomID)
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM YearT;"
'new: debug statement
Debug.Print sqlSTR
db.Execute sqlSTR
And I got an "Object variable or With block variable not set" error. What am I doing wrong?
Edit: Setting the db to Currentdb fixes the Object variable error, but now returns a "Too few parameters" error. The original table name "Year" has been changed to "YearT," since I only reference it in this one bit of code anyway.
Update
Now that I've fixed RegistrationFsub, it seems that the button also inserts data currently displayed in other controls on the form. So if the 2012 entry has RID = 1 and Leader = True, the above code creates an entry in Registration that also has RID = 1 and Leader = True. How can I keep those other fields blank?
The object variable error is because you didn't Set db to anything before you attempted db.Execute. Do this first ...
Set db = CurrentDb
If you later get an error with Execute, it may be because Year is a reserved word. Enclose that table name in square brackets to avoid confusing the db engine.
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM [Year];"
If you are adding a new record based on the Mom's current new entry, you need to take the current time: Now() and parse the year off of it..
Year(Now())
Looking for Max(YearStart) could be looking for a record that happened 5 years ago..
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM Year;"
I think you need to update the code to two different operations:
sqlSTR = "INSERT INTO Registration(Year(Now()), MomID)"
run your code..
Then do a..
sqlSTR= "SELECT Year(Now()), " & IDvar & " AS expr1 FROM [Year];"
The most relevant answer was deleted before it could be selected, so I shall paste the content here:
The object variable error is because you didn't Set db to anything before you attempted db.Execute. Do this first ...
Set db = CurrentDb
If you later get an error with Execute, it may be because Year is a reserved word. Enclose that table name in square brackets to avoid confusing the db engine.
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM [Year];"
For "too few parameters", add Debug.Print sqlSTR after the sqlSTR = ... line.
But before the Execute command
Run the code and go to the Immediate window (Ctrl+g). Copy the SQL text, create a new query in the query designer, switch to SQL View, and paste in the SQL text. When you run that query, Access will pop up an input box asking you to supply a value for the parameter. That box also include the name of whatever Access thinks is the parameter.
The trouble here is that YearStart had a different field name in table Year.
Many thanks for the clear and helpful answer.

Converting in VBA Access

I have a question with my converting in VBA. I made a button in a form and when I press it, it should make an update in my database table, but I get an ERROR:
arithmetic overflow error converting numeric to data type numeric
How can solve this problem? Here is my code:
Private Sub Inserare_Click()
Dim strSQL As String
Dim rst As New ADODB.Recordset
strSQL = "UPDATE dbo.Soferi_test SET number= '" &
Me![subform_soferi].Form!certificat_cipti & _
"',drivers= '" & Me![subform_soferi].Form!categorii_permis & _
"' WHERE IDNO = " & Forms!Forma_redactare_soferi!IDNO
Call AttServ(strSQL, rst)
MsgBox ("Datele au fost introduse cu success")
End Sub
number is a reserved word. Bracket that name in your UPDATE statement so the db engine knows it's supposed to be a field name.
strSQL = "UPDATE dbo.Soferi_test SET [number]= '" &
If that change doesn't resolve the problem, inspect the completed SQL statement. Insert this line after you store the string to strSQL.
Debug.Print strSQL
You can view that output in the Immediate window (go there with Ctrl+g). You can then copy that statement text into SQL View of a new Access query for testing. Add the statement to your question if you can't get it to work properly and tell us whether you get the same or different error message.
It may also help to show us the code from your AttServ procedure which uses strSQL.
I think the problem is in the field type of the table you are trying to update.
Example: If you try to set the value of a small integer field to a long integer, value, Access will throw an error.
Check the type of your fields and set them to the appropriate type.
Other think that can be wrong is the value of the text boxes. Just to be sure, try to convert the values.
Example: Cdbl(Me![subform_soferi].Form!certificat_cipti) will convert the string in your text field to a double value.
Also, I recommend you use the value attribute of your text boxes:
Me![subform_soferi].Form!certificat_cipti.Value
or
CDbl(Me![subform_soferi].Form!certificat_cipti.Value)
Notice that if you use the "conversion" functions (CDbl, CInt, CDate, etc.) an error will be thrown if the conversion fails (for example, trying to convert 12abc to an integer will fail)

Access variable Field Names

In MS Access 2010, I am building an update query (using the Query Designer).
I would like to pass the name of the column to update as a variable, at run time.
I have tried writing the SQL and running the query in VBA. This seemed like the easiest way... however the SQL to complete the update becomes quite messy. I would prefer to do this in the query builder GUI .
Is it possible?
I have so far tried entering field names into the query builder:
expr1:[field_name]
Although Access prompts me for "Field_name" This results in "Cannot update 'field_name'; field not updateable.
Also, I tried this method:
Expr1: "'" & [field_name] & "'"
which results in "'" & [field_name] & "'" is not a valid name; check for punctuation.. etc
Below is a screen capture the query I am trying to build.
Access' db engine will not allow you to use a parameter as the name of the target field for your UPDATE statement.
If you try a user-defined function instead of a parameter to provide the field name, the result will be the same ... no joy.
It seems the db engine will not resolve object names when it executes a SQL statement. That limitation applies not just to field names, but table names as well. IOW, the following query will fail with an error message that it "cannot find the input table or query 'give me a table name'".
SELECT *
FROM [give me a table name];
While that isn't exactly the same as your situation, I suspect the reason may be. The db engine is too limited about resolving object names when it plans/executes queries.
Perhaps the best method is to use SQL, build your prompts and then assign these values to variables in VBA, then just add the variable value into your SQL.
So something along these lines. Your using Update query but same logic
Dim SQL as string
dim **FieldName** as string
SQL = "Select [table]![" & Chr(34) & **FieldName** & Chr(34) & "] from ........"
Check Here for SQL building tips
I use this method frequently - I know it's a very old post, but hope this helps someone - building on what David said:
Sub CreateQuery
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set dbs = CurrentDb
Set qdf = dbs.CreateQueryDef("NameOfNewQuery")
strSQL = "Select " 'notice the space
strSQL = strSQL & "FROM " 'notice the sapce
strSQL = strSQL & "WHERE;"
qdf.SQL = strSQL
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
End Sub

Access 2007 Runtime Error

I'm not sure if this is the right site to post this question, but here it goes...
In Access 2007 I get the error "Runtime Error '3061': Too few parameters. Expected 1" on this piece of VBA code:
Private Sub btnCheck_Click()
Dim rs As Recordset
Dim db As Database
Dim id As String
Dim query As String
MsgBox ("one")
Set db = CurrentDb()
id = Me.UniqueID.Value
query = "SELECT [Unique_ID] from tblPatients WHERE [Unique_ID] =" & id
MsgBox (id)
Set rs = db.OpenRecordset(query) <<<<<HIGHLIGHTED LINE
If IsNull(rs) Then
Me.lblCheck.Caption = "NEW"
Else
Me.lblCheck.Caption = "EXISTS"
End If
End Sub
The data source is a table, not a query. Any help would be much appreciated!
There is no field named Unique_ID in your table tblPatients. If you posted all of your code then that is the only possible explanation.
EDIT: Your comment confirmed my suspicions:
I just triple checked :P Table name: tblPatients Column name: Unique ID
You added an underscore in your code that did not exist in your field name. You are correct in using square brackets, but the correct code should be:
query = "SELECT [Unique ID] from tblPatients WHERE [Unique ID] =" & id
Please note the removed underscores. Alternatively (and I'd say preferably if you are in the early stages of design), you can rename the field in the table to either Unique_ID or UniqueID and save yourself a good deal of hassle.
A Few things can cause this error. A common error is misspelled table names and field names.
I would check tblPatients is spelled correctly or that there is no prior suffix like dbo.tblPatients required if the table is linked to a Server Connection.
As well we are assuming the id is a number and isn't a text field which would cause an error if you do not have the correct quotes. ie.
it would instead read
query = "SELECT [Unique_ID] from tblPatients WHERE [Unique_ID] = '" & id & "';"
Lastly, try to place ";" like I did in the line above.
I suggest you add a Debug.Print statement to your code like this:
query = "SELECT [Unique_ID] from tblPatients WHERE [Unique_ID] =" & id
Debug.Print "query: " & query
The reason for that suggestion is Debug.Print will print your SQL statement to the Immediate Window. (You can use the Ctrl+g keyboard shortcut to get to the Immediate Window.) Then you can view the completed string you're asking OpenRecordset to use. Often just seeing that string (rather than trying to imagine what it should look like) will let you spot the problem. If not, you can copy the string from the Immediate Window and paste it into SQL View of a new query ... the query designer can help you pinpoint syntax errors ... or in this case, I think it may alert you to which item in your query the database engine doesn't recognize and suspects must therefore be a parameter. And if that step still doesn't resolve the problem, you can paste the string into your question on Stack Overflow.
Finally, I think you may have a logic error with IsNull(rs) ... because rs has been declared a recordset, it will never be Null. In the following example, the SELECT statement returns no records. And the Debug.Print statement says IsNull(rs): False both before and after OpenRecordset.
Public Sub RecordsetIsNeverNull()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSql As String
strSql = "SELECT * FROM tblFoo WHERE 1 = 2;"
Set db = CurrentDb
Debug.Print "IsNull(rs): " & IsNull(rs)
Set rs = db.OpenRecordset(strSql)
Debug.Print "IsNull(rs): " & IsNull(rs)
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Edit: According to Problem names and reserved words in Access, query is an Access reserved word. I don't actually think that is the cause of your problem, but suggest you change it anyway ... perhaps strQuery.

Microsoft Access Append Querydef for Memo Field

I am getting an vba error 3271; Invalid property value. This happens when trying to append a memo field in a querydef. Any ideas on how to get around this?
Example:
public sub TestMemoField
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("AppendRecord")
qdf.Parameters("#SomeBigText").value = string(1000,"A")
qdf.Execute
end sub
Thanks in advance.
Apparently you cannot have a parameter longer than 255 characters ( http://support.microsoft.com/kb/275116 ).
It is possible to use a recordset, or to use:
qdf.SQL="INSERT INTO Sometable (SomeField) Values('" & String(1000, "A") & "')"
Um, what are you trying to do? Why are you using parameters? Why not just execute SQL in code, like this:
Public Sub TestMemoField
Dim strSQL As String
strSQL = "UPDATE MyTable SET MyField='" & String(1000,"A") & "'"
CurrentDb.Execute strSQL, dbFailOnError
End Sub
I don't use parameters in saved queries except when I need to pull a value from a control on a form to be used in a saved query.
Now, my answer might not be good if your back end is not Jet or if there's something about the actual criteria and structure of your saved query that makes it important to use a saved query instead of simply using on-the-fly SQL. But you've provided virtually no information (including omitting the SQL of the querydef you're executing), so it's rather difficult to supply any kind of helpful answer.