Access variable Field Names - ms-access

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

Related

Passing a variable into SQL With VBA/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 & "'")

VBA OpenRecordset Produces Error 3061

databasename = "qryDataExport"
Dim grpfield As String
grpfield = "Group"
Dim keys As DAO.Recordset
groupcmd = "SELECT [" & databasename & "].[" & grpfield & "] FROM [" & databasename & "] GROUP BY [" & databasename & "].[" & grpfield & "]"
Set keys = CurrentDb.OpenRecordset(groupcmd, dbOpenSnapshot)
The above produces "Error 3061: Too few parameters. Expected 13." when run. My reading thus far has heavily implied that this is likely a spelling issue with improper field titles or an issue caused by improper quotations in the line defining groupcmd.
I have attempted the following formats for databasename:
CurrentDb.Queries.qryDataExport
CurrentDb!Queries!qryDataExport
And the above "qryDataExport". The latter two provide no error messages, while the first does not compile. I have confirmed that there is a column titled Group in both the main table and in qryDataExport.
The module being used is from this Google Code page.
(EDIT: Full edited module as of this time: http://pastebin.com/TJip86ED)
From what I've seen, I expect this is an incredibly obvious formatting error in the databasename definition, but I haven't got enough experience with VBA to spot it and I'm running out of ideas. Any suggestions would be greatly appreciated.
EDIT2: The content of generateKML() is now in ExportToKMLButton_Click(), where ExportToKMLButton is a Button on the Form DW_Form. While DW_Form is open, the query qryDataExport is usable, but when the form is closed, the query prompts for the 13 parameters mentioned in the error message.
It sounds like your qryDataExport query references controls on an Access form, perhaps similar to this one ...
SELECT *
FROM YourTable
WHERE some_field = Forms!Form1!YourTextBox
If Form1 is open (in Form View), I can run that query from Access' query designer, and it will resolve the reference to the form control.
However, if I try to use the exact same query with OpenRecordset, the reference is not resolved and, in that context, Access interprets it to be a parameter for which I have not supplied a value.
For your query with multiple control references, you can create a temporary QueryDef based on your SELECT statement, and loop through its Parameters collection, supplying each parameter value with Eval() of the parameter's .Name And finally call the QueryDef.OpenRecordset method to load your recordset:
Dim prm As DAO.Parameter
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef(vbNullString, groupcmd)
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next
Set keys = qdf.OpenRecordset
The way you use databasename is correct (databasename = "qryDataExport"), qryDataExport is likely filtering data using values from the form... that's why when you execute the query independently, the query finds it is missing 13 paramenters that it takes from said form.
You can run this procedure in a Click() event for a button within the form, it should work.

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.

Errors on Opening Recordset MSAccess

I am using the following code in Access to try to open a recordset:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("fieldHistory")
I consistently get the error "Too few parameters."
fieldHistory is a query with the SQL code as follows:
SELECT Date, User, Type
FROM Inventory
WHERE ((Inventory.Type) In ("Insert","EditTo"));
I have looked into this some - I have found that if I use the code db.OpenRecordset("Select * from Inventory") I do not get an error.
Also, I found this forum which seemed to be on to something but I couldn't understand how to create the appropriate querydef objects to create my query.
http://access.mvps.org/access/queries/qry0013.htm
Thank you very much!
Date, User, and Type are all special words or reserved words in MS Access. DO NOT use them for your field names.
You may have some success by enclosing each of them in brackets but I highly recommend you change the field names instead.
Create a new database.
Open the new database and make sure you have DAO included in the references.
Insert a new standard module, making sure to include Option Explicit in the Declarations section.
Then paste in this code and run it.
Public Sub CreateTableZack()
Dim strSql As String
strSql = "CREATE TABLE tblZack (" & vbNewLine & _
vbTab & "id COUNTER CONSTRAINT pkey PRIMARY KEY," & vbNewLine & _
vbTab & "foo_text TEXT(255)," & vbNewLine & _
vbTab & "date_assigned DATETIME);"
Debug.Print strSql
CurrentProject.Connection.Execute strSql
End Sub
Assuming the table is created successfully, create qryZack with this as its SQL:
SELECT *
FROM tblZack;
Then try your code to open a DAO recordset based on qryZack.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("qryZack")
Does it work?
If not, your Access installation may be hosed ... you may need to repair or reinstall it. You could also try this on another machine which has Access available, if you can.
If it works with the new database, but not your old one, the old one may be corrupted. Make a backup copy first, then try Compact & Repair.
Another issue is your field names. Date, User and Type are all Access reserved words. See Problem names and reserved words in Access. I can't say those names are causing problems here, but using reserved names for database objects (tables, fields, queries, etc.) can have dramatic consequences ... like it confuses the crap out of Access. So I fastidiously avoid them.
Edit: You should also check the references in your old database. Missing/broken references also confuse the crap out of Access.

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.