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.
Related
Just a question. Situation is as follows:
I have 15 make table queries that pulls data for a different submission clarification code that was used on a claim; i.e. Pull all claims where submission clarification code 5. As of right now I have a macro that will run all 15 queries, but each time I am required to type in the region I am filtering for due to the [What Region?] prompt I had put in the criteria field.
My question is:
Is it possible to use VBA to run all 15 queries using the DoCmd.RunSQL where I only have to type in the region number once and it will apply it to all queries?
My initial thoughts were I would have VBA prompt me for what region I'm filtering for, store that in a variable, and then use that variable in the SQL statement. But I'm not even sure if you can do that? Thanks in advance for any advice that may be given!
Update: So after reading a few threads, I created a mock database to try out some of the concepts and I think I might be on the right track?
Private Sub btnTest_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim SQLString As String
SQLString = "SELECT tblEmployees.ID, tblEmployees.Last_Name, tblEmployees.First_Name, tblEmployees.SS_ID INTO Test" _
& "FROM tblEmployees" _
& "WHERE (((tblEmployees.ID)=[What number]));"
Set qdf = CurrentDb.QueryDefs("Query1")
qdf.Parameters(0).Value = InputBox("What is the ID Number")
qdf.Execute
qdf.Close
Set db = Nothing
Set qdf = Nothing
End Sub
So to apply this to the 15 queries I would just Dim other variables as DAO.QueryDef right? I'm note really sure i need the SQLString part either? Also, I noticed that when running this mock code it took quite a while for it to create the new table. Is this normal? Also also, the code will not run if the table it is creating already exists. Is there a way to just have the code replace the existing table with the new one? Kind of new to this VBA so thanks for your patience.
Short answer is yes, this is possible. Some keywords you want to familiarize yourself with are "parameters" which are the variables with the prompt and "Querydef" or query definition.
There are quite a few articles detailing how to pass parameter values to a query programmatically. Check out this page for a solid overview of how to accomplish this. Most notably, the last example uses an inputbox to prompt the user to provide the parameter value, which gets you close to what you need. (ie. cmd.Parameters(0).Value = InputBox("Enter a country name"))
Modified to your design, it might be best to create a string variable and ask for the parameter first, then use the variable in declaring the parameters individually, which would permit a single parameter submission that gets applied to all queries.
EDIT
I have adjusted your code to show you how to go about it. You will have to repeat the block for each query.
Private Sub btnTest_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strParamter As String
Set db = CurrentDb
strParamter = InputBox("What is the ID Number")
Set qdf = db.QueryDefs("Query1")
qdf.Parameters(0).Value = strParameter
qdf.Execute
qdf.Close
'Now move to next query
Set qdf = db.QueryDefs("Query2")
qdf.Parameters(0).Value = strParameter
qdf.Execute
qdf.Close
'...etc.
Set qdf = Nothing
Set db = Nothing
End Sub
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
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.
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.
HI,
I am trying to write a query in vba and to save its result in a report.
I am a beginner. this is what i have tried
can somebody correct me
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim sql As String
Set cn = CurrentProject.Connection
sql = "Select * from table1 where empno is 0"
rs.Open sql, cn
While Not rs.EOF
' here i think i should save the result in a report but i am not sure how
rs.MoveNext
Wend
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Also how do i change this query to run this on all tables in a database
IF you are wanting to create a report using MS Access's report generator, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort).
You can create the Query Object on the "Database" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name.
Similarly the report can be created on the "Database" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created.
Update: As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway.
The problem with this method is you would have to create a separate query and report for each table.
IF you just want to dump the result out to a text file (to read/print later), then you can do it using recordsets like you are in your VBA code. It will look something like this
'...
dim strFoo as string
dim strBar as string
'...
if not rs.bof then
rd.MoveFirst
end if
While Not rs.EOF
strFoo = rs("foo") 'copy the value in the field
'named "foo" into strFoo.
strBar = rs("bar")
'... etc. for all fields you want
'
'write out the values to a text file
'(I'll leave this an exercise for the reader)
'
rs.MoveNext
Wend
'...
Parsing all of the tables can be done in a loop something like this:
dim strTableName as string
dim db As Database
'...
Set db = CurrentDb
db.TableDefs.Refresh
For Each myTable In db.TableDefs
If Len(myTable.Connect) > 0 Then
strTableName = myTable.Name
'...
'Do something with the table
'...
End If
Next
set db = nothing
=======================UPDATE=======================
It is possible to run an MS-Access Report from a record set. To repease what I said to tksy's question
From Access Web you can use the "name" property of a recordset. You resulting code would look something like this:
In the report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
In the calling object (module, form, etc.)
Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
Q.E.D.
Normally you would design the report based on a data source. Then after your report is done and working properly you use VBA to display or save the report.
To run this for each table in the database, I'd suggest writing a function that looped through CurrentData.AllTables(i) and then called your function above in each iteration
Hope this helps
If you want to simply view the results, you can create a query. For example, here is some rough, mostly untested VBA:
Sub ViewMySQL
Dim strSQL as String
Dim strName As String
'Note that this is not sensible in that you
'will end up with as many queries open as there are tables
For Each tdf In CurrentDB.TableDefs
If Left(tdf.Name,4)<>"Msys" Then
strName = "tmp" & tdf.Name
strSQL = "Select * from [" & tdf.Name & "] where empno = 0"
UpdateQuery strName, strSQL
DoCmd.OpenQuery strName, acViewNormal
End If
Next
End Sub
Function UpdateQuery(QueryName, SQL)
If IsNull(DLookup("Name", "MsysObjects", "Name='" & QueryName & "'")) Then
CurrentDb.CreateQueryDef QueryName, SQL
Else
CurrentDb.QueryDefs(QueryName).SQL = SQL
End If
UpdateQuery = True
End Function
You may also be interested in MDB Doc, an add-in for Microsoft Access 97-2003 that allows you to document objects/properties within an Access database to an HTML file.
-- http://mdbdoc.sourceforge.net/
It's not entirely clear to me what you want to do. If you want to view the results of SQL statement, you'd create a form and set its recordsource to "Select * from table1 where empno is 0". Then you could view the results one record at a time.
If that's not what you want, then I'm afraid I just don't have enough information to answer your question.
From what you have said so far, I don't see any reason why you need VBA or a report, since you just want to view the data. A report is for printing, a form is for viewing and editing. A report is page-oriented and not that easy to navigate, while a form is record-oriented, and allows you to edit the data (if you want to).
More information about what you want to accomplish will help us give you better answers.
Had the same question. just use the clipboard!
select the query results by click/dragging over all field names shown
press ctrl-c to copy to windows clipboard
open a blank document in word and click inside it
press ctrl-v to paste from clipboard.