disabling the bypass key - ms-access

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

Related

Check if DSN exist in excel vba

I have a excel workbook connected to a MySQL server. I placed a refresh button that refresh the data and it holds unprotect and protect statements for the sheet.
My problem is when open the excel file and click on refresh in a computer that is not in the network, I get a get a DSN creating wizard and also If I press cancel in the wizard the sheet becomes unprotected.
I want to place a IF condition that checks if the DSN is available and if not it should exit sub.
Any ideas?
This is my code with error handler, but I still get the DSN creation wizard and after the msgbox is closed the sheet is unprotected
On Error GoTo handler
Application.ScreenUpdating = False
Sheets("DEC-2015").Unprotect Password:="password"
ActiveWorkbook.Connections("Query from Sample").Refresh
Sheets("DEC-2015").Protect _
Password:="password", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True
handler:
MsgBox "Server Connection Lost...", vbOKOnly + vbCritical, "Warning"
Exit Sub
Turn alerts off by altering your code to the following:
Public Sub DoSomething()
On Error GoTo handler
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
With ThisWorkbook
.Sheets("DEC-2015").Unprotect Password:="password"
.Connections("Query from Sample").Refresh
.Sheets("DEC-2015").Protect _
Password:="password", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True
End With
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
Exit Sub
handler:
ThisWorkbookSheets("DEC-2015").Protect _
Password:="password", _
UserInterfaceOnly:=True, _
AllowFiltering:=True, _
AllowSorting:=True, _
AllowUsingPivotTables:=True
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
MsgBox "Server Connection Lost...", vbOKOnly + vbCritical, "Warning"
End Sub

Enable AllowBypassKey based off password

I have a created a database that has the AllowBypassKey shift key disabled. What I am trying to do is have a hidden box that when double clicked on pops up a box where the user must enter the password and then the AllowBypassKey is enabled. I have added the code I have written so far but I am getting a "Sub or Function not defined" for the SetProperties portion. I have shown the disable AllowBypassKey code as well.
Disable Bypass code:
Function ap_DisableShift()
On Error GoTo errDisableShift
Dim db As DAO.Database
Dim prop As DAO.Property
Const conPropNotFound = 3270
Set db = CurrentDb()
db.Properties("AllowByPassKey") = False
Exit Function
errDisableShift:
If Err = conPropNotFound Then
Set prop = db.CreateProperty("AllowByPassKey", _
dbBoolean, False)
db.Properties.Append prop
Resume Next
Else
MsgBox "Function 'ap_DisableShift' did not complete successfully."
Exit Function
End If
End Function
Double-Click Code (Error popping up!)
Private Sub Secret_DblClick(Cancel As Integer)
On Error GoTo Err_bDisableBypassKey_Click
Dim strInput As String
Dim strMsg As String
Beep
strMsg = "Do you want to enable the Bypass Key"
strInput = InputBox(Prompt:=strMsg, Title:="Disable Bypass Key Password")
If strInput = "PASSWORD" Then
SetProperties "AllowBypassKey", dbBoolean, True
Beep
MsgBox "The Bypass Key has been enabled."
Else
Beep
SetProperties "AllowBypassKey", dbBoolean, False
MsgBox "Incorrect ''AllowBypassKey'' Password!"
Exit Sub
End If
Exit_bDisableBypassKey_Click:
Exit Sub
Err_bDisableBypassKey_Click:
MsgBox "bDisableBypassKey_Click", Err.Number, Err.Description
Resume Exit_bDisableBypassKey_Click
End Sub
You can use Allen Browne's SetPropertyDAO and HasProperty functions to manage the AllowBypassKey setting. (Source for those functions is here; and also included at the bottom of this answer.)
Then to normally disable AllowBypassKey for all users at database start, create this function and call it from the RunCode action of your database's AutoExec macro:
Public Function StartUp()
SetPropertyDAO CurrentDb, "AllowBypassKey", dbBoolean, False
End Function
To allow your privileged user(s) to override that setting (IOW to enable AllowBypassKey), use this tested version of your Secret_DblClick procedure:
Private Sub Secret_DblClick(Cancel As Integer)
Dim strInput As String
Dim strMsg As String
On Error GoTo Err_bDisableBypassKey_Click
Beep
strMsg = "Do you want to enable the Bypass Key"
strInput = InputBox(Prompt:=strMsg, Title:="Disable Bypass Key Password")
If strInput = "PASSWORD" Then
SetPropertyDAO CurrentDb, "AllowBypassKey", dbBoolean, True
Beep
MsgBox "The Bypass Key has been enabled."
Else
Beep
SetPropertyDAO CurrentDb, "AllowBypassKey", dbBoolean, False
MsgBox "Incorrect 'AllowBypassKey' Password!"
End If
Exit_bDisableBypassKey_Click:
Exit Sub
Err_bDisableBypassKey_Click:
MsgBox "bDisableBypassKey_Click", Err.Number, Err.Description
Resume Exit_bDisableBypassKey_Click
End Sub
Function SetPropertyDAO(obj As Object, strPropertyName As String, intType As Integer, _
varValue As Variant, Optional strErrMsg As String) As Boolean
On Error GoTo ErrHandler
'Purpose: Set a property for an object, creating if necessary.
'Arguments: obj = the object whose property should be set.
' strPropertyName = the name of the property to set.
' intType = the type of property (needed for creating)
' varValue = the value to set this property to.
' strErrMsg = string to append any error message to.
If HasProperty(obj, strPropertyName) Then
obj.Properties(strPropertyName) = varValue
Else
obj.Properties.Append obj.CreateProperty(strPropertyName, intType, varValue)
End If
SetPropertyDAO = True
ExitHandler:
Exit Function
ErrHandler:
strErrMsg = strErrMsg & obj.Name & "." & strPropertyName & " not set to " & _
varValue & ". Error " & Err.Number & " - " & Err.Description & vbCrLf
Resume ExitHandler
End Function
Public Function HasProperty(obj As Object, strPropName As String) As Boolean
'Purpose: Return true if the object has the property.
Dim varDummy As Variant
On Error Resume Next
varDummy = obj.Properties(strPropName)
HasProperty = (Err.Number = 0)
End Function

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

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

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.

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