I have an Access database with many year-specific table names (not my design). I want to copy the DB to a new DB and update all tables to have the same name but updated from "xxx_2007" to "xxx_2008", and have all queries that reference "2007" updated to reference "2008" instead. These references might be in table names or may be selection criteria in the query.
The approach I'm using now is to open each query, copy the SQL to notepad, replace "2007" with "2008", then copy it back to the SQL view of the query. It's workable, but tedious.
Any suggestions on programmatic way to update everything?
What Gord said.
But if you really need a quick hack to make it work right now, you can loop the QueryDefs collection:
Dim DB As Database
Dim QD As QueryDef
Dim S As String
Set DB = CurrentDb
For Each QD In DB.QueryDefs
S = QD.SQL
If InStr(S, "2007") > 0 Then
S = Replace(S, "2007", "2008")
QD.SQL = S
End If
Next QD
Similar with TableDefs for table names, here you would replace TD.Name
I also recommend what Gord stated. If not, simply use Rick Fisher's Find and Replace http://www.rickworld.com/products.html.
Related
I have a continuous form in MS Access that I would like to create a table from. Most of the fields are populated by a query, but some fields will be user entered and there will also be calculated fields. Basically I need to create a snapshot of the data when a users clicks a button at any given point and then save the table with the value of one of the fields and that particular date. What is the best way to achieve this?
Thank you!
-Charlie
What you actually want to do is learn how to use recordset clones. You should also reuse a table seeing in how there is a pretty good chance you'll want fresh data on each pull.
Because this isnt a code writing service, ill let you figure out the details, but this should be plenty to get you started.
Sub Print_Field_Names()
Dim rst As Recordset, intI As Integer
Dim fld As Field
dim vbSql as string
vbSql = "DELETE * FROM Tbl"
DoCmd.RunSQL vbSql
Set rst = Me.RecordsetClone
For Each fld in rst.Fields
' Print field names.
Debug.Print fld.Name
Next
End Sub
In the loop through the original recordset clone, you should try for yourself how to edit another recordset on your reusuable table to "Fill" the new table with your form data. this is actually really simple and the masochist in me wants you to actually suffer since you didnt try anything on your own first :P
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
I am trying to run the following code to loop around a recordset and do updates where neccessary.
I have a Microsoft Access database connected to a MySql backend. Whenever I run this code I get the following error:
3197 error: The Microsoft Office Access database engine stopped the process because you and another user are attempting to change the same data at the same time.
The code is below:
Private Sub test()
Dim rs As DAO.Recordset, rsCnt As Long, i As Long
Set rs = CurrentDb.OpenRecordset("qryMyQuery", DB_OPEN_DYNASET)
rs.MoveLast
rsCnt = rs.RecordCount
rs.MoveFirst
For i = 1 To rsCnt
rs.Edit
rs!MyFieldInTable = "test"
rs.Update
Next i
End Sub
I thought the Access database might be corrupt so I pulled an earlier backup but it's doing the same thing which makes me think it's a MySql issue.
We use an identical piece of code on another version of this database linked to a different MySql table and it works fine.
Also, when I open the query the record-set is based on I can edit the data in the query without any issues.
Just to add, on the first loop, rs!MyFieldInTable is updated, then I get the error.
It does not appear that you are moving to another record in the recordset. Simply incrementing i doesn't move to the next record. A more traditional approach would be to iterate over the recordset without the need for your other variables (i and rsCnt).
Dim rs as DAO.Recordset
Set rs = CurrentDb.OpenRecordset("qryMyQuery", DB_OPEN_DYNASET)
rs.moveFirst
Do Until rs.EOF
rs.Edit
rs!FieldNameHere = "test"
rs.Update
rs.MoveNext
Loop
EDIT
After a bit of searching I came across this thread which seems to be similar to your issue. At the bottom of the thread a suggestion is made to modify the ODBC settings for your MySQL DSN by selecting the "Advanced" tab and selecting the option to "Return Matching Rows". The post also says to drop the linked table and then re-link it to your Access database.
I haven't used Access with MySQL in the past, so I have no idea whether this will work or not, so proceed with caution!
You may also try changing your recordset to use the dbOptimistic flag for the recordset locking option to see if that helps at all:
set rs = CurrentDB.OpenRecordSet("qryMyQuery", DB_OPEN_DYNASET, dbOptimistic)
Two things you can try. First, try adding the dbSeeChanges option when opening the recordset:
Dim rs as DAO.Recordset, db As DAO.Database
Set db = Currentdb
Set rs = db.OpenRecordset("qryMyQuery", dbOpenDynaset, dbSeeChanges)
Do Until rs.EOF
rs.Edit
rs!FieldNameHere = "test"
rs.Update
rs.MoveNext
Loop
The other option, as #HansUp suggested, is to use a SQL update statement instead of a dynamic recordset. The key there is to open the recordset as a snapshot, so that changes you make to the records do not affect the recordset itself.
Dim rs as DAO.Recordset, db As DAO.Database
Set db = Currentdb
Set rs = db.OpenRecordset("qryBatchPayments", dbOpenSnapshot)
Do Until rs.EOF
db.Execute "UPDATE Payments " & _
"SET DCReference='test' " & _
"WHERE PaymentID=" & !PaymentID, dbFailOnError
rs.MoveNext
Loop
I was having the same problem and my solution turned out to be the default value for BIT(1) fields. Access does not like these to be null. Make sure you use either 0 or 1 in mysql for these fields.
I don't have MySQL here to try this against, but it looks to me as if your code is not advancing the recordset after the rs.Update method is executed, so that you are trying to udate the same field in the fierst record.
Add this line after the rs.Update:
rs.MoveNext
Hope that helps.
Try calling OpenRecordset from an object variable set to CurrentDb(), rather than directly from CurrentDb().
Dim rs as DAO.Recordset
Dim db As DAO.Database
Set db = Currentdb
Set rs = db.OpenRecordset("qryMyQuery", DB_OPEN_DYNASET)
rs.moveFirst
Do Until rs.EOF
rs.Edit
rs!FieldNameHere = "test"
rs.Update
rs.MoveNext
Loop
The reason for that suggestion is I've found operations on CurrentDb directly can throw an error about "block not set". But I don't get the error when using an object variable instead. And ISTR OpenRecordset was one such operation where this was an issue.
Also, my impression was your approach is a cumbersome way to accomplish the equivalent of:
UPDATE qryMyQuery SET FieldNameHere = "test";
However, I suspect the example is a proxy for a real world situation where the recordset approach is useful. Still that makes me wonder whether you would see the same or a different error when executing the UPDATE statement.
If you continue to have trouble with this, it may help to show us the SQL View for qryMyQuery.
I have discovered that if one tries to save data which are the same as the one already in the MySql record Access will display this kind of error. I've tried some suggestions from this thread but did not help.
The simple solution for this is to save a slightly diffrent data by using a manual time-stamp. Here is an example of heaving a sort order field and setting it to 10, 20, 30...
i = 10
timeStamp = Now()
Do Until Employee.EOF
Employee.Edit
Employee!SortOrderDefault = i
Employee!LastUpdated = timeStamp
Employee.Update
i = i + 10
Employee.MoveNext
Loop
I've tried automatic time-stamp in the MySql table but did not help when the new entry data is the same as the old one.
My little helpful hint is, bits are very, very, very bad data types to use when linking SQL tables to Microsoft Access because only SQL Server understands what a bit is, Microsoft Access has a hard time interpreting what a bit is. Change any bit datatypes to int (integers) and relink your tables that should clear things up. Also, make sure your Booleans always contain a 1 or a 0 (not a yes/no or a true/flase) in your VBA code or your updates will fail to the linked SQL tables because Microsoft Access will try to update them with a True/False or a Yes/No and SQL will not like that.
I also had same problem; i solved them adding those to code using dao.recordset:
**rst.lockedits = true**
rst.edit
rst.fields(...).value = 1 / rst!... = 1
rst.update
**rst.lockedits = false**
this seems fix conflict between just opened data (such as in a form) and updating them with code.
Sorry for my bad english... i read a lot but i never had learn it! I'm just italian.
I have an Access 2010 database with a VBA module that does some statistical analysis on the data. The results of the statistical analysis cannot be generated by SQL, but they can be presented in tabular format. Right now, I can run the VBA function in the Immediate window and it will loop over the results and write them to the terminal using Debug.Print().
I'd like to have the results of this function available to the rest of Access so that I can create queries and reports from the table of results. So what I'm looking for is how to turn my function into a "dynamic table" -- a table that doesn't actually store data, but stores the VBA function that runs and fills in the table data dynamically whenever that table is used.
I've spent quite a bit of time looking at creating tables dynamically via MAKE TABLE queries or using DDL in VBA, but all of these examples use SQL to create the new table from existing records. I can't use SQL to generate the results, so I'm not really sure how to coerce the results into an object that Access will recognize. Part of the problem is that I'm just not familiar enough with Access VBA terminology to know what I should be looking for.
My declaration is just "Public Function GenerateSchedule" . It has three code blocks: the first pulls the data I need from the database using a query and processes the RecordSet into an array. The second block performs the statistical analysis on the array, and the third prints the results of the analysis to the terminal. I'd like to replace the third block with a block that provides the results as a table that is usable by the rest of Access.
I use following code if I don't want to use DDL and SQL Query...
Set dbs = CurrentDb
Set tbl = dbs.CreateTableDef("tbl_Name")
Set fld = tbl.CreateField("Field1", dbText, 255)
tbl.Fields.Append fld
Set fld = tbl.CreateField("Field2", dbText, 255)
tbl.Fields.Append fld
Set fld = tbl.CreateField("Field3", dbInteger)
tbl.Fields.Append fld
Set fld = tbl.CreateField("Field4", dbCurrency)
tbl.Fields.Append fld
dbs.TableDefs.Append tbl
dbs.TableDefs.Refresh
and if you want to add a record you could do
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
Set rstVideos = dbs.OpenRecordset("tbl_name")
rs.AddNew
rs("field1").Value = "TEST "
rs("field2").Value = "TEXT"
rs("field3").Value = 1991
rs("field4").Value = 19.99
rstVideos.Update
I am not sure why you need to put the retrieved data into an array. It seems and extra step. If you can generate the statistics from the array, the same thing should be possible in a query. create another query, using the results query as one recordsource and make your calculations accordingly for the fields that you want created.
If we saw what you were trying to do, I think it could be made more simple.
This sounds like a disconnected recordset, or maybe "synthetic recordset," which is something ADO can do. I don't use ADO, so can't provide you with instruction, but maybe that will provide you with what you need.
Alternatively, depending on how you want to display it to the users, you might be able to do it native in Access. For instance, if presenting it on a form or report in a listbox is sufficient, then you could write a custom callback function and bind it to the listbox.
So lets say I have some code like below to pull data from another access file:
Sub ADO_Recordset_OpenTable()
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim MyPath As String
MyPath = CurrentProject.Path
Set cn = New ADODB.Connection
cn.Provider = "Microsoft Jet 4.0 OLE DB Provider"
cn.ConnectionString = "Data Source=C:\Users\Justin\Desktop\ExampleFile.mdb"
cn.Open
Set rs = New ADODB.Recordset
rs.Open "Schedule", cn, adOpenDynamic, adLockReadOnly, adCmdTable
' I would like to at this point build a table within the currentdb file
' with the data in the recordset. Either some kind of create table or
' SQL INSERT?? Just trying to learn how to work with the data set
So within the example are my comments. Basically would like to know how to create a table out of the data contained with the recordset. I guess creating a tabledef? But this is DAO right? and I couldn't really use both DAO and ADO together in a routine right?
Thanks
Justin
You can use both ADO and DAO for different objects within the same procedure.
You could create a DAO.TableDef and examine the recordset's Fields collection, creating new TableDef fields matching each rs.Fields(i).Name and rs.Fields(i).Type
Once you have created the table structure (TableDef), you can loop through the recordset rows to build and execute INSERT statements to store the row values in your new table.
But that seems like waaaay too much work to me. I like Raj's SELECT INTO suggestion better. However, since you already know the table name and path to your MDB, I would reach first for DoCmd.TransferDatabase, and leave ADO only for tasks DAO can't do at all or can't do as conveniently as ADO.
Finally, if your primary interest on this one is exploring possibilities, take a look at the recordset's Save method. You could save with adPersistXML, then import the saved XML as a new table in your current db. See Save Method (ADO)
I have done this the ugly way - parse the incoming ADO recordset, build the CREATE TABLE statement and execute it, and then RBAR through the ADO dataset to insert into the local table.
You can also create a passthrough query which you can then use to SELECT * INTO MyNewTable FROM MyPassThroughQuery
You could try ADOX.