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.
Related
I'm trying to get some information from a mysql database to a report in access. But I can't figure out how to get the information there since I'm using DAO connections in vba and cant use linked tables.
I've tried storing the information into a string from the form that I already have the information at through a DAO connection directly to mysql db with no luck.
Private Sub Command67_Click()
DoCmd.Save
DoCmd.GoToRecord , , acNewRec
Me.Label39.Visible = True
Dim strWhere As String
strWhere = "[ID] = " & Me.[Id]
DoCmd.OpenReport "MyReport", acViewPreview, , strWhere
End Sub
I use preview in that code to see some result but what I would like to do is print directly to the printer since this is a client turn receipt i need those to print fast.
Again I can't use linked tables.
After investigating on your former questions (some should be linked to that question), I see the problem. You don't link the MySQL-Tables what would make things easier for you.
But you can still use queries! Just put your connection string (maybeGlobales.ConnStringin former questions) in the queriesODBC Connection Stringin query design->properties. That makes the query a passthrough-query that is passed to MySQL-Server directly, not using MDAC.
Just set the reportsRecordSourceto the name of the query.
You can also build the query in VBA, but you can't use a temporary QueryDef("") as you can't set the Reports-Recordset, so use a non temp one.
Example (assumes there is a QueryDef named QueryForReport):
Sub EditQueryDefPassthrough()
With CurrentDb.QueryDefs("QueryForReport")
.Connect = "ODBC;Driver={MySQL ODBC 5.3 ANSI Driver};" _
& "Server=YourServerName;" _
& "Database=YourDatabaseName;" _
& "User=YourMysqlUserName;" _
& "Password=MysqlPwdForUser;" _
& "Option=3;" ' adapt this to your MySQL ODBC Driver Version and server settings
.SQL = "SELECT `Field` FROM `TABLE` LIMIT 1,1;" 'put SQL here (MySQL SQL Dialect, not MS-Access!). You can't use Access functions here (like Replace(), ..., but those of MySQL like Concat().
End With
End Sub
The QueryDef needs to be set before the Report_Load Event, but in Report_Open should be sufficent (e.g. if you want to use OpenArgs for building the SQL-String)
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 trying to create a dynamic report in Excel. I have lots of sales data and I want the user to be able to slice and dice it according to his needs.
Normally I would use two sheets: one hidden, containing the raw data, and one visible, containing all the buttons and form controls so that the user can dinamically select and visualize only a small subset of the original data at the time.
The problem is that this time I need to handle 6.000.000+ rows of data (and counting). Storing it all in an excel sheet is not an option. Besides, the data is already in the form of an Access table.
I tried accessing it dinamically via a query that "filters out" the un-needed information based on what the user selects in the form control on the Excel sheet. For some reason, this is very slow. It takes 4-5 minutes to pull out as little as 10 rows of data.
There has to be a quicker way to do this! I need this whole process to feel "instantaneous".
Any thoughts?
Edit: Ok, so the problem seems to be related to the fact that my access table is actually a linked table pointing to a *.txt file. This slows the import down a lot.
I tried both of the suggested solutions.
iDevlop's idea works quite fast (200k rows imported in 10-15 secs), but it has the downside of me having to update the table every time. I'll post another question, like he suggested, to see how and if the process can be automated.
Remou's script works perfectly too now (I had a hard time getting it right but he was really open and helpful so know I got it) and, although slower, it has the advantage of not requiring any database mantainance.
There's a few more things I need to get straight before choosing which approach to use. For now, all I want to say is thank you guys for you help! I could have never made it without you!!!
Don't bother going through Access if you have a text file. This may hold you until you can get a better system in place.
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer
strFile = "z:\docs\"
''Note that if HDR=No, F1,F2 etc are used for column names,
''if HDR=Yes, the names in the first row of the range
''can be used.
''
''Connection strings : http://www.connectionstrings.com/excel
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Text;HDR=Yes;IMEX=1"";"
''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * " _
& "FROM [test.txt] a " _
& "WHERE a.FirstName ='Bernard'"
rs.Open strSQL, cn, 3, 3
''Pick a suitable empty worksheet for the results
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
If your file is tab delimited, you can use a schema.ini (http://msdn.microsoft.com/en-us/library/ms709353(VS.85).aspx). It must be in the same directory as you text file and need only contain two lines:
[Ordini BO new.txt]
Format=TabDelimited
Your connection string should read:
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Text;HDR=No;IMEX=1;FMT=Delimited"";"
As says Remou, check xour indexes, but also make sure your criteria are entered in a way that allows indexes to be used !
e.g : WHERE Format(myDate,"yyyy-mm") = "2011-09" does not allow the date index optimisation,
while WHERE myDate BETWEEN #09/01/2011# AND #09/30/2011# does allow index optimisation.
Edit:
If you have some kind of unique identifier in your text file and you translate that into a PK in your table design, you can then import the whole thing on a regular basis, and the duplicates will be discarded by the PK.
The import could be automated, even with a .vbs, you don't need Access to do it. Make that another question if you're stuck.
You could also ask the IT guys to delete the older records every month or so.
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 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.