compile error: expected end of statement - ms-access

A Microsoft Access 2010 database is giving me the following error message:
Compile Error: Expected End Of Statement
Here is the method that is throwing the error message:
Private Sub Form_BeforeUpdate(Cancel As Integer)
'Provide the user with the option to save/undo
'changes made to the record in the form
If MsgBox("Changes have been made to this record." _
& vbCrLf & vbCrLf & "Do you want to save these changes?" _
, vbYesNo, "Changes Made...") = vbYes Then
DoCmd.Save
Else
DoCmd.RunCommand acCmdUndo
End If
Dim sSQL As String
sSQL = "SELECT max(Clients.ClientNumber) AS maxClientNumber FROM Clients"
Dim rs As DAO Recordset
Set rs = CurrentDb.OpenRecordset(sSQL)
MsgBox ("Max client number is: " & rs.Fields(1))
End Sub
The line of code that is throwing the error message is:
Dim rs As DAO Recordset
I am not sure if the problem has to do with the syntax of what is on the line preceding it. Can anyone show how to fix this problem? And explain what is going on?

You are missing a full stop (period) between the DAO and the Recordset - it should be
Dim rs As DAO.Recordset
Beyond that, you will also have a runtime error on reading the field value, since a DAO Fields collection is indexed from 0, not 1. Hence, change the penultimate line to this:
MsgBox ("Max client number is: " & rs.Fields(0))
Alternatively, reference the field by its name:
MsgBox ("Max client number is: " & rs!maxClientNumber)

You're mising the semicolon at the end of your Sql statement

Related

How to resolve a "Could not find installable ISAM error in MySQL connection string in Access module

Access 365/Windows 10
I’m getting the “Could not find installable ISAM” error which I believe means I’ve a problem with my connection string below.
I did a right click, export on a single Access table to the MySQL backend so that I could link it and verify the driver, server, port, database, etc. of that connection against the connection string in the function below. It all looks good. Can you see what I've done wrong?
I have 128 tables to migrate to MySQL and am looking for a efficient, repeatable process; I had high hopes for this code...
'''
Public Function fncExportTables() As Boolean
'Declare Variables...
Dim strCnn As String
Dim rs As Recordset
Dim db As Database
Dim strTp As String
Dim strOriginal As String
'The Connection String required to connect to MySQL.
'I THINK THIS IS THE PROBLEM
strCnn = "DRIVER={MySQL ODBC 8.0 Driver};" & _
"SERVER=myServer;" & _
"PORT=24299;" & _
"DATABASE=myDb;" & _
"USER=myUserName;" & _
"PASSWORD=myPassword;" & _
"OPTION=3;"
strTp = "ODBC Database"
'Trap any Errors...
On Error GoTo Error_fncExportTables
'Open a recordset from the table the conatains
'all the table names we want to Link from the
'MySQL Database.
Set db = CurrentDb
Set rs = db.OpenRecordset("qselMgr", dbOpenSnapshot)
With rs
'Fill the Recordset...
.MoveLast
.MoveFirst
'Enumerate through the Records...
Do Until rs.EOF
'Place the Table Name into the str string variable.
' FieldName (below) would be the Field name in your Access
' Table which holds the name of the MySQL Tables to Link.
strOriginal = !strOriginalName
'Make sure we are not dealing will an empty string..
If Len(strOriginal) > 0 Then
'Link the MySQL Table to this Database.
'ERROR TRIGGERS ON THE LINE BELOW
DoCmd.TransferDatabase acExport, strTp, strCnn, _
acTable, strOriginal, strOriginal
End If
'move to the next record...
.MoveNext
Loop
End With
'We're done...
Exit_fncExportTables:
'Clear Variables and close the db connection.
Set rs = Nothing
If Not db Is Nothing Then db.Close
Set db = Nothing
Exit Function
Error_fncExportTables:
'If there was an error then display the Error Msg.
MsgBox "Export Table Error:" & vbCr & vbCr & _
Err.Number & " - " & Err.Description, _
vbExclamation, "Export Table Error"
Err.Clear
Resume Exit_fncExportTables
End Function
'''

Ignore error 58 when renaming files

I've got a small Access program that looks up files names from a query ("qryImagesToRename"), goes through a loop and renames them. However, if an image already exists with the same name Access wants to rename it to, I receive
error 58 - File Already Exists
How do I ignore this error and continue with the loop? This my code:
Private Sub Command10_Click()
On Error GoTo Command10_Click_Error
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
DoCmd.Hourglass True
Set db = CurrentDb
strSQL = "select * from qryImagesToRename"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
Name rs.Fields("From").Value As rs.Fields("To").Value
rs.MoveNext
Loop
DoCmd.Hourglass False
MsgBox "All matching files renamed"
On Error GoTo 0
Exit Sub
Command10_Click_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Command10_Click of VBA Document Form_frmRename - Please take a screenshot and email xxxxxx#xxxxxxx.com"
End Sub
If you are certain that you can ignore the error then you could use On Error Resume Next to ignore it and continue processing. Ensure that you add On Error Goto 0 as soon as you can, to reinstate the normal error processing.
On Error Resume Next
Do While Not rs.EOF
Name rs.Fields("From").Value As rs.Fields("To").Value
rs.MoveNext
Loop
On Error GoTo 0
This is most often a poor practice, but can be used if there is certainty about behaviour.
A better practice would be to check if the file already exists using Dir (or FileSystemObject) and skip it. Discussed here
Two particular solutions come to mind. The first, is in-line logic to check for the existing file, and skip that item, and the second is to put a case statement in the error handler. I have outlined the code below to have both options. I hope it helps.
Private Sub Command10_Click()
On Error GoTo Command10_Click_Error
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
Dim fso as New FileSystemObject
DoCmd.Hourglass True
Set db = CurrentDb
strSQL = "select * from qryImagesToRename"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF 'if you want to use the logic inline, use the check below
If fso.fileexists(rs.Fields("To").value) = false Then
Name rs.Fields("From").Value As rs.Fields("To").Value
End If
NextRecord: 'if you want to use the goto statement, use this
rs.MoveNext
Loop
DoCmd.Hourglass False
MsgBox "All matching files renamed"
On Error GoTo 0
Exit Sub
Command10_Click_Error:
Select case Err.number
Case 58
GoTo NextRecord
Case Else
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Command10_Click of VBA Document Form_frmRename - Please take a screenshot and email xxxxxx#xxxxxxx.com"
End select
End Sub

Why do I get run-time error '2759' when saving the record? access 2010

Using Access 2010, I have a form for Purchase_Orders where the status changes depending on the whether the Items in the sub form have been delivered or not, and, it is influenced by the date as well.
Private Sub Form_AfterUpdate()
Dim rs As Recordset
Dim db As Database
Dim var_Delivered As String
var_Delivered = "SELECT Count(*) AS d_Count" & _
" FROM Items" & _
" WHERE PO_ID =" & Me.PO_ID.Value & _
" AND Supplier_Dnote_ID IS Null" & _
" AND Delivered_Without_Dnote =0;"
Set db = CurrentDb
Set rs = db.OpenRecordset(var_Delivered, dbOpenDynaset)
'MsgBox rs!d_Count
If rs!d_Count > 0 Then
If Me.Supply_date < Date Then
Me.Status = "Overdue"
Else
Me.Status = "Submitted"
End If
Else
Me.Status = "Delivered"
End If
db.Close
Set db = Nothing
Set rs = Nothing
End Sub
This runs after_update of the Purchase_Orders. I have a save_close button that uses the following code and doesn't return an error:
If Me.Dirty = True Then
DoCmd.Close acForm, "Purchase_Orders", acSaveYes
Else
DoCmd.Close acForm, "Purchase_Orders", acSaveNo
End If
However, I also have a Save button that doesn't close the form. This is where I get run-time error 2759 : The method you tried to invoke on an object failed. Debug Highlights the saverecord line.
Private Sub SaveOnlyBtn_Click()
If Me.Dirty = True Then
docmd.RunCommand acCmdSaveRecord
End If
End Sub
If I comment the status code out and use the save button, the record saves fine without any errors. Why do I get this error? I'm completely stumped and searching the error online hasn't helped me either.
So I found that the error did not occur when I put the code in the "on dirty" event, which then made me realise that I don't need necessarily have to run the code after the form updates, only when specific fields change. So I changed my code to a public code and called it when supply date, delivered_without_dnote, or supplier_Invoice_ID changed.
the public code is :
Public Sub delivered_status()
On Error GoTo errTrap1
If Forms!Purchase_Orders_Ex.Form!Status = "Cancelled" Then
Exit Sub
Else
DoCmd.RunCommand acCmdSaveRecord
Dim rs As Recordset
Dim db As Database
Dim var_Delivered As String
var_Delivered = "SELECT Count(*) AS d_Count" & _
" FROM Items" & _
" WHERE PO_ID =" & Forms!Purchase_Orders_Ex.Form!PO_ID.Value & _
" AND Supplier_Dnote_ID IS Null" & _
" AND Delivered_Without_Dnote =0;"
Set db = CurrentDb
Set rs = db.OpenRecordset(var_Delivered, dbOpenDynaset)
'MsgBox "Outstanding Items: " & rs!d_Count
If rs!d_Count > 0 Then
If Forms!Purchase_Orders_Ex.Form!Supply_date < Date Then
Forms!Purchase_Orders_Ex.Form!Status = "Overdue"
Else
Forms!Purchase_Orders_Ex.Form!Status = "Submitted"
End If
Else
Forms!Purchase_Orders_Ex.Form!Status = "Delivered"
End If
rs.Close
Set db = Nothing
Set rs = Nothing
End If
errTrap1:
Select Case Err.Number
Case 3314 'form not complete and other required fields are empty
Exit Sub
Case Else
If Err.Number > 0 Then
MsgBox Err.Number & ": " & Err.Description
End If
End Select
End Sub
Now, when I use either the save_close or Save_Only I do not get error 2759. I do not completely understand which part of my original method caused the error but it no longer occurs with this approach.
I've just encountered this issue and moving code out of Form_AfterUpdate fixed it for me too.
What's (vaguely) interesting is that the code in question worked fine locally, but did not work when deployed to the client. I tried importing just the amended form instead of replacing the whole access app, but I still got the same issue. I also copied the back-end database back from the server to my development machine, but still didn't get the issue locally. On top of that I did endless compact/repair and decompile/compile.
My conclusion at the end of all of that was that this was yet another weird issue emanating from the Access black-box, rather than an issue with the particular code.

Message reason why Execute method failed

I use the DAO method Execute to delete some records. If this fails this is clear by checking RecordsAffected (it will be 0). But is it possible to get the error message (for instance, to log or to show to the user)? I've try to delete the records by hand in the Table grid I get a clear dialog message, e.g. "The record cannot be deleted or changed because tabel x includes related records".
Include the dbFailOnError option with the Execute method to capture your DELETE errors. Without dbFailOnError, your DELETE can fail silently.
Relying on RecordsAffected to indicate a DELETE failure can be misleading. For example if your DELETE includes "WHERE Sample=5", and there is no row with a Sample value of 5, RecordsAffected will be 0. That is not an error to the database engine.
In the following sample, the DELETE fails because there is a relationship, with referential integrity enforced, between tblParent and tblChild. So the message box says "The record cannot be deleted or changed because table 'tblChild' includes related records".
Public Sub DeleteFailure()
Dim strSql As String
Dim strMsg As String
Dim db As DAO.Database
On Error GoTo ErrorHandler
strSql = "DELETE FROM tblParent WHERE id = 1;"
Set db = CurrentDb
db.Execute strSql, dbFailOnError
ExitHere:
On Error GoTo 0
Debug.Print "RecordsAffected: " & db.RecordsAffected
Set db = Nothing
Exit Sub
ErrorHandler:
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ") in procedure DeleteFailure"
MsgBox strMsg
GoTo ExitHere
End Sub
Update: Here is a revised ErrorHandler to accommodate multiple errors triggered by a DAO operation.
ErrorHandler:
Dim errLoop As Error
Debug.Print "Errors.Count: " & Errors.Count
For Each errLoop In Errors
With errLoop
strMsg = "Error " & Err.Number & " (" & _
Err.Description & _
") in procedure DeleteFailure"
End With
MsgBox strMsg
Next
Set errLoop = Nothing
GoTo ExitHere
It should be possible to use DBEngine errors: http://msdn.microsoft.com/en-us/library/bb177491(office.12).aspx

Access 2007 DAO VBA Error 3381 causes objects in calling methods to "break"

---AFTER FURTHER INVESTIGATION---
"tblABC" in the below example must be a linked table (to another Access database).
If "tblABC" is in the same database as the code then the problem does not occur.
Hi,
We have recently upgraded to Office 2007.
We have a method in which we have an open recordset (DAO). We then call another sub (UpdatingSub below) that executes SQL. This method has its own error handler. If error 3381 is encountered then the recordset in the calling method becomes "unset" and we get error 3420 'Object invalid or no longer set'. Other errors in UpdatingSub do not cause the same problem.
This code works fine in Access 2003.
Private Sub Whatonearth()
Dim rs As dao.Recordset
set rs = CurrentDb.OpenRecordset("tblLinkedABC")
Debug.Print rs.RecordCount
UpdatingSub "ALTER TABLE tblTest DROP Column ColumnNotThere"
'Error 3240 occurs on the below line even though err 3381 is trapped in the calling procedure
'This appears to be because error 3381 is encountered when calling UpdatingSub above
Debug.Print rs.RecordCount
End Sub
Private Sub WhatonearthThatWorks()
Dim rs As dao.Recordset
set rs = CurrentDb.OpenRecordset("tblLinkedABC")
Debug.Print rs.RecordCount
'Change the update to generate a different error
UpdatingSub "NONSENSE SQL STATEMENT"
'Error is trapped in UpdatingSub. Next line works fine.
Debug.Print rs.RecordCount
End Sub
Private Sub UpdatingSub(strSQL As String)
On Error GoTo ErrHandler:
CurrentDb.Execute strSQL
ErrHandler:
'LogError'
End Sub
Any thoughts? We are running Office Access 2007 (12.0.6211.1000) SP1 MSO (12.0.6425.1000). Perhaps see if SP2 can be distributed?
Sorry about formatting - not sure how to fix that.
That error indicates that there is no such column in the table. The code above can only be run once. You may wish to check that the column (field) exists before you delete it.
Edited after comment:
Private Sub Whatonearth()
Dim rs As DAO.Recordset
strColName = "ColumnNotThere"
Set rs = CurrentDb.OpenRecordset("tblABC")
For Each fld In rs.Fields
If fld.Name = strColName Then
Debug.Print rs.RecordCount
''The recordset will have to be closed
''before calling UpdatingSub
rs.Close
UpdatingSub "ALTER TABLE tblABC DROP Column " & strColName
''Debug.Print rs.RecordCount
Exit For
End If
Next
End Sub
''To get a proper error with SQL, you need dbFailOnError
''You may also need to loop through the errors collection*
Private Sub UpdatingSub(strSQL As String)
On Error GoTo ErrHandler
CurrentDb.Execute strSQL, dbFailOnError
ErrHandler:
''LogError
Debug.Print Err.Description
End Sub
'' Enumerate Errors collection and display properties of
'' each Error object.
For Each errLoop In Errors
With errLoop
strError = _
"Error #" & .Number & vbCrLf
strError = strError & _
" " & .Description & vbCrLf
strError = strError & _
" (Source: " & .Source & ")" & vbCrLf
End With
Thanks for all your input - and sorry for any confusion re my problem - it was a weird one. I tried it on a PC running
Office Access 2007 (12.0.6423.1000) SP2 MSO (12.0.6425.1000)
rather than
Office Access 2007 (12.0.6211.1000) SP1 MSO (12.0.6425.1000)
and I do not get the same problem. Time to see if we can get the powers to be to install the newer version.
I'm glad that someone else has also encountered this problem. I had exactly the same issue (error 3381 causing problems with DAO recordset), and also with pass through queries running SQL statements on SQL Server 2000.
Once I prevented the error 3381 from occuring (by checking for the existence of the field before trying to DROp it from a table), no further problems.
For what it's worth, I was running Office Access 2007 (12.0.6211.1000) SP1 MSO (12.0.6320.5000).
Definitely seems like an Access DAO issue that Microsoft may have resolved with later Service Pack.