Can't save to local table when network access is interrupted. - ms-access

I have a split database where the backend is located remotely; when I get the error "Network access has been interrupted" I want to log something on a local table for future access. After creating a system for this I found out that when the connection is lost to the remote backend the local tables also become inaccessible.
While I don't think there is necessarily a solution to this I want to find out why the local tables aren’t accessible when clearly they shouldn't require a network connection to be used. The following is the code for my function that I use to try and log locally.
Public Function LogTempError(ByVal lngErrNumber As Long, _
ByVal strErrDescription As String, _
strCallingProc As String, _
Optional varParameters As Variant, _
Optional blnSHOW_USER As Boolean = True) As Boolean
On Error GoTo Err_Handler
'Set warnings to True just in case the error happened while they were set to false.
DoCmd.SetWarnings True
Dim rs As DAO.Recordset
Set rs = DBEngine(0)(0).OpenRecordset("TempErrorTable", dbOpenDynaset, dbAppendOnly)
With rs
.AddNew
!ERROR_LOG_NUMBER = lngErrNumber
!ERROR_LOG_USERID = NetworkUserName()
!ERROR_LOG_DESCRIPTION = strErrDescription & " logged from Temp Table"
!ERROR_LOG_TIMESTAMP = Now()
!ERROR_LOG_FORM = strCallingProc
.Update
End With
Exit_Handler:
On Error Resume Next
rs.Close
Set rs = Nothing
Exit Function
Err_Handler:
If DateDiff("s", dteLAST_ERROR_TIME, Now()) > 20 Or lngLAST_ERROR_NUMBER <> lngErrNumber Then
' If there are more errors that can't be logged, simply email the errors.
SendEmail "First Unloggable error", "Error Num: " & Err.Number & " Error Description: " & strErrDescription & " From: " & strCallingProc
SendEmail "Second Unloggable error", "Error Num: " & Err.Number & " Error Description: " & Err.Description & " From: " & strCallingProc
MsgBox "An error occured that wasn't able to be logged, a message was sent to Database Administrator on your behalf.", vbInformation, "Notification Sent"
End If
Resume Exit_Handler
End Function

Try this slightly stripped-down version, which opens the connection to TempErrorTable on first use, and keeps the connection open. Let it stop on errors within LogTempError so you can see where the TempErrorTable update is failing.
Public Function LogTempError(ByVal lngErrNumber As Long, _
ByVal strErrDescription As String, _
strCallingProc As String, _
Optional varParameters As Variant, _
Optional blnSHOW_USER As Boolean = True) As Boolean
Static rs As Recordset
On Error GoTo 0
DoCmd.SetWarnings True
If rs Is Nothing Then ' open recordset on first use
Set rs = CurrentDb.OpenRecordset("TempErrorTable", dbOpenDynaset, dbAppendOnly)
End If
With rs
.AddNew
!ERROR_LOG_NUMBER = lngErrNumber
!ERROR_LOG_USERID = NetworkUserName()
!ERROR_LOG_DESCRIPTION = strErrDescription & " logged from Temp Table"
!ERROR_LOG_TIMESTAMP = Now()
!ERROR_LOG_FORM = strCallingProc
.Update
End With
Exit Function

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
'''

How to encrypt Access with password using code?

I created a Deploy Access file which I use to deploy my production Access file. This re-links tables to production SQL server, incorporates disabling use of Shift, add new version number.... I need also encrypt the production Access file with a password. This should be done using code in my Deploy Access file but I cannot find a way to do it. Any ideas? Thanks.
Try this function:
Public Function SetDatabasePassword(strDatabasePath As String, Optional pNewPassword As Variant, Optional pOldPassword As Variant) As String
On Error GoTo SetDatabasePassword_Error
DoCmd.Hourglass True
Const cProvider = "Microsoft.ACE.OLEDB.12.0"
Dim cnn As ADODB.Connection
Dim strNewPassword As String
Dim strOldPassword As String
Dim strCommand As String
Dim strResult As String
' If a password is not specified (IsMissing), ' the string is "NULL" WITHOUT the brackets
If IsMissing(pNewPassword) Then
strNewPassword = "NULL"
Else
strNewPassword = "[" & pNewPassword & "]"
End If
If IsMissing(pOldPassword) Then
strOldPassword = "NULL"
Else
strOldPassword = "[" & pOldPassword & "]"
End If
strCommand = "ALTER DATABASE PASSWORD " & strNewPassword & " " & strOldPassword & ";"
Set cnn = New ADODB.Connection
With cnn
.Mode = adModeShareExclusive
.Provider = cProvider
If Not IsMissing(pOldPassword) Then
.Properties("Jet OLEDB:Database Password") = pOldPassword
End If
.Open "Data Source=" & strDatabasePath & ";"
.Execute strCommand
End With
strResult = "Password Set"
ExitProc_:
On Error Resume Next
cnn.Close
Set cnn = Nothing
SetDatabasePassword = strResult
DoCmd.Hourglass False
Exit Function
SetDatabasePassword_Error:
DoCmd.Hourglass False
If Err.Number = -2147467259 Then
strResult = "An error occured"
ElseIf Err.Number = -2147217843 Then
strResult = "Invalid password"
Else
strResult = Err.Number & " " & Err.Description
End If
Resume ExitProc_
Resume ' use for debugging
End Function

disabling the bypass key

I would like to disable the bypass key of my database on the open form event during the autoexec so that the user is not able to view the underlying tables of my form. I have found the following code and creatd a module to run upon opening the form during the auto exec. The module is called SetBypass
Call SetBypass
Option Compare Database
Public Function SetByPass(rbFlag As Boolean, File_name As String) As Integer
DoCmd.Hourglass True
On Error GoTo SetByPass_Error
Dim db As Database
Set db = DBEngine(0).OpenDatabase(File_name)
db.Properties!AllowBypassKey = rbFlag
setByPass_Exit:
MsgBox "Changed the bypass key to " & rbFlag & " for database " & File_name, vbInformation, "Skyline Shared"
db.Close
Set db = Nothing
DoCmd.Hourglass False
Exit Function
SetByPass_Error:
DoCmd.Hourglass False
If Err = 3270 Then
' allowbypasskey property does not exist
db.Pro perties.Append db.CreateProperty("AllowBypassKey", dbBoolean, rbFlag)
Resume Next
Else
' some other error message
MsgBox "Unexpected error: " & Error$ & " (" & Err & ")"
Resume setByPass_Exit
End If
End Function
The above module need to be called form out side the application
try the below code if you are in same database
Sub blockBypass()
Dim db As Database, pty As DAO.Property
Set db = CurrentDb
On Error GoTo Constants_Err 'Set error handler
db.Properties("Allowbypasskey") = False
db.Close
Constants_X:
Exit Sub
Constants_Err:
If Err = 3270 Then 'Bypass property doesn't exist
'Add the bypass property to the database
Set pty = db.CreateProperty("AllowBypassKey", dbBoolean _
, APP_BYPASS)
db.Properties.Append pty
Resume Next
End If
MsgBox Err & " : " & Error, vbOKOnly + vbExclamation _
, "Error loading database settings"
End Sub

VBA DoCmd.OutputTo With QueryDef

I've been looking a while now for a solution to export a query with open parameters. I need to export a Query as a Formatted Excel Spreadsheet and can't create additional Tables, Queries, Forms, or Reports to the Database being used. I use DoCmd.OutputTo as it exports a formatted query unlike DoCmd.TransferSpreadsheet however I can't seem to export the query with defined parameters. I need to include the parameters or else the user will be forced to input the start and end date three times a piece as the database for some reason asks for the startDate and endDate twice and in order to keep the excel spreadsheet and the subsequent outlook section consistant i would have to ask the user to input their previous parameters again
Sub Main()
On Error GoTo Main_Err
'Visually Display Process
DoCmd.Hourglass True
Dim fpath As String
Dim tname As String
Dim cname As String
Dim tType As AcOutputObjectType
Dim tempB As Boolean
fpath = CurrentProject.path & "\"
'tType = acOutputTable
'tname = "APPROVED SWPS FOR LOOK AHEAD & BAR CHART"
tType = acOutputQuery
tname = "ASFLA&BC Query"
cname = "Temp BPC Calendar"
Dim qdfQry As DAO.QueryDef
Dim strStart As String
Dim strEnd As String
Set qdfQry = CurrentDb().QueryDefs(tname)
'strStart = InputBox("Please enter Start date (mm/dd/yyyy)")
'strEnd = InputBox("Please enter Start date (mm/dd/yyyy)")
qdfQry.Parameters("ENTER START DATE") = FormatDateTime("6/30/12", vbShortDate) 'strEnd
qdfQry.Parameters("ENTER END DATE") = FormatDateTime("7/1/12", vbShortDate) 'strStart
tempB = Backup(fpath, qdfQry, tType)
If (Not tempB) Then
MsgBox "Excel Conversion Ended Prematurely..."
Exit Sub
End If
' tempB = sendToOutlook(qdfQry, cname)
' If (Not tempB) Then
' MsgBox "Access Conversion Ended Prematurely..."
' Exit Sub
' End If
MsgBox "Procedure Completed Successfully"
Main_Exit:
DoCmd.Hourglass False
Exit Sub
Main_Err:
DoCmd.Beep
MsgBox Error$
Resume Main_Exit
End Sub
'************************************************************************************
'*
'* Excel PORTION
'*
'************************************************************************************
Public Function Backup(path As String, db As DAO.QueryDef, Optional outputType As AcOutputObjectType) As Boolean
On Error GoTo Error_Handler
Backup = False
Dim outputFileName As String
Dim name As String
Dim tempB As Boolean
'Set Up All Name Variablesand
name = Format(Date, "MM-dd-yy") & ".xls"
'Cleans Directory of Any older files and places them in an archive
SearchDirectory path, "??-??-??.xls", name
'See If File Can Now Be Exported. If Already Exists ask to overwrite
outputFileName = path & name
tempB = OverWriteRequest(outputFileName)
If tempB Then
'Formats The Table And Exports Into A Formatted SpreadSheet
'Checks if an output type was added to the parameter if not defualt to table
If Not IsMissing(outputType) Then
DoCmd.OutputTo outputType, db.name, acFormatXLS, outputFileName, False
Else
DoCmd.OutputTo acOutputTable, db.name, acFormatXLS, outputFileName, False
End If
Else
Exit Function
End If
Backup = True
Error_Handler_Exit:
Exit Function
Error_Handler:
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
Err.number & vbCrLf & "Error Source: Main Excel Backup" & vbCrLf & "Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
The SQL currently given looks like similar to below with omitted fields for for clarity
PARAMETERS [ENTER START DATE] DateTime, [ENTER END DATE] DateTime;
SELECT [SWPS].STATION,
[SWPS].START_DATE,
[SWPS].END_DATE,
FROM [SWPS]
WHERE ((([SWPS].STATION)
Like ("*"))
AND (([SWPS].START_DATE)<=[ENTER END DATE])
AND (([SWPS].END_DATE)>=[ENTER START DATE])
AND (([SWPS].SWP_STATUS) In ("A","P","W","T","R")));
I suggest you change the sql of the query.
Dim qdfQry As DAO.QueryDef
Dim strStart As String
Dim strEnd As String
''You could use a query specifically for this
Set qdfQry = CurrentDb.QueryDefs(tname)
sSQL=qdfQry.SQL
NewSQL = "SELECT [SWPS].STATION, [SWPS].START_DATE, [SWPS].END_DATE, " _
& "FROM [SWPS] WHERE [SWPS].STATION Like '*' " _
& "AND [SWPS].SWP_STATUS In ('A','P','W','T','R') " _
& "AND [SWPS].START_DATE)<=#" & Format(DateStart, "yyyy/mm/dd") & "# " _
& "AND [SWPS].END_DATE)>=#" & Format(DateEnd, "yyyy/mm/dd") & "#"
qdfQry.SQL = NewSQL
''Do the excel stuff
''Reset the query
qdfQry.SQL = sSQL

Re-Link to new mdb then delete old database (mdb)

I have a procedure where the ultimate objective is to update all tables on a server backend database from a laptop. Once this is complete, I want to delete the local (laptop) mdb and replace the deleted file (mdb) with the server mdb.
All seems to work well except I can't delete the local version even though I have re-linked the laptop front end to the server backend. Here is my code:
Call CloseALLFormsReports
Call RelinkTables("K:\Proposals\Northway\Data\Northway Data.accdb")
******************************************
'backup current c: database
tBackupfile = "C:\Proposals\backup\Northway DATA" & Format(Now(), "yyyymmdd hhmm") & ".accdb"
Call TransferBEData("C:\Proposals\Northway DATA.accdb", tBackupfile)
'now overwrite c:drive file
Call TransferBEData("K:\Proposals\Northway\Data\Northway Data.accdb", "C:\Proposals\Northway DATA.accdb")
Call RelinkTables("C:\Proposals\Northway DATA.accdb")
*************HERE IS THE TransferBEDate function:
Function TransferBEData(ByVal tSource As String, ByVal tDestination As String)
If FileExists(tDestination) Then
Kill tDestination
End If
FileCopy tSource, tDestination
End Function
************HERE IS MY Relinking Function
Public Sub RelinkTables(strNewPath As String)
Dim dbs As DAO.Database
Dim tdf As TableDef
Dim intCount As Integer
Dim frmCurrentForm As Form
Dim relink As Boolean
DoCmd.Hourglass True
On Error GoTo ErrLinkUpExit
'Me.lblMsg.Visible = True
'Me.cmdOK.Enabled = False
Set dbs = CurrentDb
For intCount = 0 To dbs.TableDefs.Count - 1
Set tdf = dbs.TableDefs(intCount)
If tdf.Connect <> "" Then
'Me.lblMsg.Caption = "Refreshing " & tdf.Name
DoEvents
tdf.Connect = ";DATABASE=" & strNewPath
tdf.RefreshLink
End If ' tdf.Connect <> ""
Next intCount
Set dbs = Nothing
Set tdf = Nothing
DoCmd.Hourglass False
MsgBox ("The file: " & strNewPath & " was successfully linked.")
'Me.lblMsg.Caption = "All Links were refreshed!"
relink = True
'Me.cmdOK.Enabled = True
Exit Sub
ErrLinkUpExit:
DoCmd.Hourglass False
Select Case Err
Case 3031 ' Password Protected
MsgBox "Back End '" & strNewPath & "'" & " is password protected"
Case 3011 ' Table missing
DoCmd.Hourglass False
MsgBox "Back End does not contain required table '" & _
tdf.SourceTableName & "'"
Case 3024 ' Back End not found
MsgBox "Back End Database '" & strNewPath & "'" & " " & _
"Not Found"
Case 3051 ' Access Denied
MsgBox "Access to '" & strNewPath & "' Denied " & _
vbCrLf & _
" May be Network Security or Read Only Database"
Case 3027 ' Read Only
MsgBox "Back End '" & strNewPath & "'" & " is Read " & _
"Only "
Case 3044 ' Invalid Path
MsgBox strNewPath & " Is Not a Valid Path"
Case 3265
MsgBox "Table '" & tdf.Name & "'" & _
" Not Found in ' " & strNewPath & "'"
Case 3321 ' Nothing Entered
MsgBox "No Database Name Entered"
Case Else
MsgBox "Uncaptured Error " & Str(Err) & " " & _
Err.Description
End Select
Set tdf = Nothing
relink = False
'******************Get rid of blank records
DoCmd.SetWarnings False
DoCmd.OpenQuery "Delete_Blank_Material_Records"
DoCmd.SetWarnings True
'********************************************
End Sub
Function TransferBEData(ByVal tSource As String, ByVal tDestination As String)
If FileExists(tDestination) Then
Kill tDestination
End If
FileCopy tSource, tDestination
End Function
The reason this doesn't work, is because re-linking the tables to another source will not delete the entry from the .mdw lock file (or security equivalent in later versions than 03). You would need to close your front-end database and then re-open in order to unlock the local .mdb file.