VBA issue with running "delete" SQL strings & append queries - vba

I have this VBA code below, which runs on open of a form in MS Access. This code is meant to delete all records from several tables, and then run saved append queries (that are quite complex) to fill in those tables once again, with fresh data every time.
The form that opens (after this code runs) is based on the last table that gets updated in the code sequence (PDSForecast), and I have confirmed that the append query for that table works and loads the correct data in.
The issue though is, when the form based on that table is opened (which triggered this code to run in the first place), all the records show up as #Deleted for some reason, even though the append query that populates the table this form is based on is the last piece of code that runs before the form opens, and it works. Can someone help me understand what I'm doing wrong here?
Thanks!
Private Sub Form_Open(Cancel As Integer)
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE FROM ECIInventTransIntentDim"
DoCmd.RunSQL "DELETE FROM CurrentOH"
DoCmd.RunSQL "DELETE FROM CurrentOO"
DoCmd.RunSQL "DELETE FROM RequirementsAXAPTA"
DoCmd.RunSQL "DELETE FROM AvgWeeklyUsage"
DoCmd.RunSQL "DELETE FROM PDSForecast"
DoCmd.OpenQuery "Query_ECIINVENTTRANSINVENTDIM"
DoCmd.OpenQuery "Query_CURRENTOH"
DoCmd.OpenQuery "Query_CURRENTOO"
DoCmd.OpenQuery "Query_REQUIREMENTSAXAPTA"
DoCmd.OpenQuery "Query_AVGWEEKLYUSAGE"
DoCmd.OpenQuery "Query_PDSFORECAST"
DoCmd.SetWarnings True
End Sub

It sounds like your form is bound to the data table. What you should do is unbind the form before the series of queries are run and then re-bind. Your code will look similar to this:
frmMain.DataSource = nothing
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE ..."
... etc.
DoCmd.SetWarnings True
frmMain.DataSource = "myTable"

Related

VBA in MS Access: how to accelerate a loop operation on a recordset

In a database under my maintenance (MS Access 2010) I use a VBA procedure for cleaning up records, concretely: setting values in a field from "yes" to "no". The procedure loops through all records and sets the values in the respective field as required.
My database has about 900 records so far. Not too many, one should think.
My problem: the VBA procedure operates very slowly. On my current machine I have to wait for about 10 seconds until the loop has gone through the 900 records. That's impractical in everyday work.
What I need: I am looking for ways to speed this up, either through improvements to the code, or through a completely different approach.
Here is my procedure:
Private Sub WipeSelectionMarks_Click()
'Remove any filter that might be set to reduce the number of records in
'the form - We want here to operate on all records in the database!
Me.Filter = ""
Me.FilterOn = False
'Don't know if we really need two commands here; but at least it works
'Operate on a recordset that holds all the records displayed in the form
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
rs.MoveFirst
Do Until rs.EOF
With rs
.Edit
!Int_IwSelectMove = False
.Update
End With
rs.MoveNext
Loop
'Message box with info what has been done
MsgBox "A total of " & rs.RecordCount & " records were updated by wiping the Move mark"
'Cleaning up
Set rs = Nothing
Me.Refresh
End Sub
Note 1: if a solution would be using an SQL command instead, I will be grateful for practical hints or examples. I use SQL commands at many places, still, getting put on the right track here would be helpful.
Note 2: Or can the VBA procedure be rewritten in a way that only records where the field in question has value "yes" are processed (these are usually only 20-30 of the 900), and those with "no" are left out?
You can use the UPDATE command:
CurrentDb.Execute "UPDATE YourTable SET Int_IwSelectMove = False"
can the VBA procedure be rewritten in a way that only records where
the field in question has value "yes" are processed
Indeed, and that may very well be the fastest method, as you will not have to requery the form:
With rs
Do Until .EOF
If !Int_IwSelectMove.Value = True Then
.Edit
!Int_IwSelectMove = False
.Update
End If
.MoveNext
Loop
.Close
End With
Or you could use FindFirst or a filtered recordset. Running SQL on the recordset of a form is usually the last option.

Run-time error 2465 can't find the field '|1' with alter column

My code:
Private Sub UpdateTables_Click()
DoCmd.SetWarnings False
MsgBox "Please Wait for the 'Done' message to appear"
DoCmd.RunMacro "Update_Tables"
DoCmd.RunSQL "ALTER TABLE " & [tablename] & " ALTER COLUMN StartDateAll DATE;"
MsgBox "Done"
DoCmd.SetWarnings True
End Sub
The DoCmd.RunSQL line is what is highlighted in the Debug window. I started with my table name as t_tablename and got a Syntax error. After reading I found that the "" might be a problem so I dropped the "t", that got rid of my syntax error but now I'm getting this 2465 error. My column was originally "Start_Date_All", so I renamed to "StartDateAll"
I have a multiple make table queries which combines start dates for employees in various departments, the resulting combined column is text instead of date. I have a button on a form which runs the above code to run a macro which runs the make table queries and that runs fine, but it gets stuck at this alter table part (which I just included one for test purposes)
I've checked the spelling of the column name, tried it with double quotes, also tried with "& StartDateAll &" ...got the 2465 error each time.
This is where you said Access complains it can't find the field:
DoCmd.RunSQL "ALTER TABLE " & [tablename] & " ALTER COLUMN StartDateAll DATE;"
There is a better approach, which may not solve the problem, but should at least give you a better chance to understand why it happens:
Dim strTable As String
Dim strAlter As String
strTable = "t_tablename"
DoCmd.SetWarnings True
strAlter = "ALTER TABLE [" & strTable & "] ALTER COLUMN StartDateAll DATE;"
Debug.Print strAlter '<- inspect in Immediate window; Ctrl+g will take you there
CurrentProject.Connection.Execute strAlter
MsgBox "Done"
I tested that code in Access 2010 with StartDateAll as a text field in t_tablename. The code ran without error and afterward I confirmed the field had been changed from Text to Date/Time datatype.
Key points there are:
Give yourself an opportunity to examine the completed ALTER TABLE statement you're asking the db engine to execute --> Debug.Print strAlter. IOW, make sure it is what you intend.
Your table name, t_tablename, should not require bracketing. But if you want to bracket the name, move those brackets inside the string segments.
Turning off SetWarnings suppresses information. When troubleshooting you want every last tidbit of information you can get. So keep SetWarnings on when you execute the ALTER TABLE.
If Access still can't find the StartDateAll field, double check the names of the fields which Access thinks do exist. Here is an example from an Immediate window session:
set db = currentdb
for each fld in db.TableDefs("t_tablename").Fields : ? fld.name : next
id
StartDateAll

MS Access VBA issue

I'm making a report in MS Access - what I'm trying to do here is basically APPEND a query to a table that I've already created - I select the first value, change it and update the table. The issue that I'm coming across is - this report will be used by a VB6 application. So the user won't be seeing Access at all.
The thing with my append query is that it needs a USER ID to run (4 digit number). Normally when I run a report in Access I pass the parameters to a form in Access - and I use them to run queries. However, in this case, I need the user to enter a value when appending the query, additionally, when appending a query in VBA it first says "You are about to append a query, are you sure" (or something along those lines), so is there a way to automate that as well, so when I append it nothing happens?
Here is my code for appending and selecting date from the tempTable:
CurrentDb.Execute "DELETE from [tempCompanyMgmt-NOW];"
DoCmd.OpenQuery "qryCompanyMgmt-SUE" - i made this append!
Set rs1 = CurrentDb.OpenRecordset("Select * from [tempCompanyMgmt-NOW]", , dbOpenDynamic)
So as long as I press OK, YES when I get notified of the APPEND process and enter the parameter for USER ID - everything works fine.
Looks like a typo in your markdown, should the 2nd line be:
DoCmd.OpenQuery "qryCompanyMgmt-SUE - i made this append!"
You'll need to remove the reference to the form inside the qryCompanyMgmt-SUE - i made this append! query, and swap it for a parameter name. You can use the Access interface to explicitly add a parameters clause to the query, and then using ADO (or DAO) from VB6, set a parameter value before you open/execute the query.
The "You are about to append a query, are you sure" message is an Access feature (and it can be disabled), so if you want the VB6 application to provide such a warning, then you'll need to create it yourself with a MsgBox.
One option would by putting your append query into the code and filling in the parameter that way.
I don't know your exact scenario, but something like:
If not isValidUserID(me.UserID) Then
msgbox "Please enter a a valid user id"
exit sub
End If
Dim strSQL As String
strSQL = "DELETE * from [tempCompanyMgmt-NOW];"
CurrentDb.Execute strSQL, dbFailOnError
strSQL = "INSERT INTO tempCompanyMgmt-NOW ( FieldName1, FieldName2, FieldName3 ) " & _
"SELECT FieldName1, FieldName2, FieldName3 FROM tempCompanyMgmt WHERE UseriD=" & Me.UserID
CurrentDb.Execute strSQL, dbFailOnError
To validate the user id you could do something like:
If (Len(me.UserID) = 4 And IsNumeric(me.UserID)) Then
or
Public Function isValidUserID(varUserID As Variant) As Boolean
Dim blnRet As Boolean
If Len(varUserID) = 4 And IsNumeric(varUserID) Then
blnRet = True
End If
isValidUserID = blnRet
End Function
To get rid of the MsgBox telling me I'm about to append a query i included this in my module before I open my append query..
DoCmd.SetWarnings False
And I realized once I have the value passed to the form (userID), that value gets passed on as a parameter when my query gets appended. So it's all set. Thanks for all help!

MS Access - execute a saved query by name in VBA

How do I execute a saved query in MS Access 2007 in VBA?
I do not want to copy and paste the SQL into VBA. I rather just execute the name of the query.
This doesn't work ... VBA can't find the query.
CurrentDb.Execute queryname
You can do it the following way:
DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("yourQueryName")
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.
To use CurrentDb.Execute, your query must be an action query, AND in quotes.
CurrentDb.Execute "queryname"
Thre are 2 ways to run Action Query in MS Access VBA:
You can use DoCmd.OpenQuery statement. This allows you to control these warnings:
BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs
Function RunActionQuery(QueryName As String)
On Error GoTo Hell 'Set Error Hanlder
DoCmd.SetWarnings True 'Turn On Warnings
DoCmd.OpenQuery QueryName 'Execute Action Query
DoCmd.SetWarnings False 'Turn On Warnings
Exit Function
Hell:
If Err.Number = 2501 Then 'If Query Was Canceled
MsgBox Err.Description, vbInformation
Else 'Everything else
MsgBox Err.Description, vbCritical
End If
End Function
You can use CurrentDb.Execute method. This alows you to keep Action Query failures
under control. The SetWarnings flag does not affect it. Query is executed always without warnings.
Function RunActionQuery()
'To Catch the Query Error use dbFailOnError option
On Error GoTo Hell
CurrentDb.Execute "Query1", dbFailOnError
Exit Function
Hell:
Debug.Print Err.Description
End Function
It is worth noting that the dbFailOnError option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified
In addition, you can use DoCmd.Hourglass True and DoCmd.Hourglass False to control the mouse pointer if your Query takes longer

SQL Query to VBA and display result in Form

So I have a few Queries already written and my goal is to have a user input certain fields that would change the way the Query is returned, basically having the user change 2 or 3 parameters of the original Query.
First, I'm having problems getting a Query to execute in VBA:
Private Sub QResultButton_Click()
DoCmd.OpenQuery (Readings2009, acViewPreview,acReadOnly)
End Sub
[Readings2009 is a Query I created in Access] This returns a syntax error.
I have also see this done:
strSQL = "SELECT Readings2009.id, Readings2009.othercolumn, Readings2009.another
WHERE Readings2009.something > today() ..."
DoCmd.RunSQL (strSQL)
I can't get either to work. Any help would be greatly appreciated.
In this example, the name of the query must be a string, that is, it must be in quotes:
DoCmd.OpenQuery "Readings2009"
See: http://msdn.microsoft.com/en-us/library/aa220295(office.11).aspx
The other example is for running action queries,not for opening queries to view them.
It would be best to create a form and to use that to display your query.