Check if DSN exist in excel vba - mysql

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

Related

How to run access event procedure from vb script after form open

The following vb code opens up a database form at a specific record. I would then like to run the event procedure that is attached to a button on the form. I have tried creating a Macro that runs the procedure, but when running the vb script, it says the procedure cannot be found. I have even tried changing the event procedure from private to public with no avail. I have also even tried just putting the name of the procedure instead of the Macro1 and still a no go. What could I possibly be missing.
Here is the vb Script:
Set accessApp = CreateObject("Access.Application")
accessApp.OpenCurrentDataBase "M:\Shared Documents\Job Cost Analysis\TRAINING JOBCOST ANALYSIS DATABASE\Job_Cost_Analysis_Tracking_Training.accdb", false
accessApp.visible = true
accessApp.UserControl = true
accessApp.DoCmd.OpenForm "frmClients", , , "Clients!client_id= 100005 ", , acWindowNormal, True
accessApp.Forms("frmClients").status_ID=3
accessApp.Run "cmdImportItemStmt_Click"
accessApp.Forms("frmClients").status_ID=34
accessApp.Save
Here is the procedure in access:
Private Sub cmdImportItemStmt_Click()
On Error GoTo Problems
Dim filename As String
'***** CHECK TO MAKE SURE STATUS IS IN ITEMIZED STATEMENT IMPORT ***********
If Me.status_ID.Column(1) = 3 Then
If IsNull(Me.frmItemizedStmtTotals("AMT DISPUTED").Value) = True Then
filename = (copyQueue & "CLIENT_" & CStr(Me.client_ID.Value) & "\Client_" & CStr(Me.client_ID.Value) & ".xlsx")
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel12, "Sheet1", filename, True
DoCmd.SetWarnings (WarningsOff)
'**********APPEND ITEMIZED STATEMENT***********
DoCmd.OpenQuery "append_itemized_stmt_import"
'**********UPDATE ITEMIZED STATEMENT W/ REASON CODES***********
DoCmd.OpenQuery "Update_reason_codes_by_desc_null_revcodes"
DoCmd.OpenQuery "Update_reason_codes_by_desc"
'************** If facility is OHSU remove non-billable items per contract**********
If Me.facility_ID = 102 Then
DoCmd.OpenQuery "qryOHSU_nonbillable"
End If
'**************************************************************
Me.frmISAmtsByRevenueCodes.Requery
Me.frmItemizedStmtTotals.Requery
DoCmd.DeleteObject acTable, "Sheet1"
DoCmd.SetWarnings (WarningsOn)
Else
MsgBox "UNABLE TO IMPORT IS RECORDS BECAUSE THE ITEMIZED" & vbCrLf & _
"STATEMENT'S TOTAL BILLED CHARGES ALREADY HAS A" & vbCrLf & _
"BALANCE > THAN ZERO INDICATING A PREVIOUS IMPORT", vbOKOnly, "UNABLE TO IMPORT IS RECORDS"
End If
Else
MsgBox "INACCURATE CLAIM REVIEW STATUS" & vbCrLf & _
"FOR ITEMIZED STATEMENT IMPORT", vbOKOnly, "INACCURATE CLAIM REVIEW STATUS"
End If
RecalculateTotals
Exit Sub
Problems:
Err.Clear
Resume Next
End Sub
VBS script for test (based on yours):
Set accessApp = CreateObject("Access.Application")
accessApp.OpenCurrentDataBase "C:\Temp\Database1.mdb"
accessApp.UserControl = true
accessApp.Run "Test1"
and test code in MS Access db.
can you run it without issue?
By changing Me. to Forms!frmClients! in the procedure I was able to get it working. I guess the vb script did not like Me. since the script is run outside of access.
Public Sub ImportItemStmt()
On Error GoTo Problems
Dim filename As String
'***** CHECK TO MAKE SURE STATUS IS IN ITEMIZED STATEMENT IMPORT ***********
If Forms!frmClients!status_ID.Column(1) = 3 Then
If IsNull(Forms!frmClients!frmItemizedStmtTotals("AMT DISPUTED").Value) = True Then
filename = (copyQueue & "CLIENT_" & CStr([Forms]![frmClients]![client_ID].Value) & "\Client_" & CStr([Forms]![frmClients]![client_ID].Value) & ".xlsx")
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel12, "Sheet1", filename, True
DoCmd.SetWarnings (WarningsOff)
'**********APPEND ITEMIZED STATEMENT***********
DoCmd.OpenQuery "append_itemized_stmt_import"
'**********UPDATE ITEMIZED STATEMENT W/ REASON CODES***********
DoCmd.OpenQuery "Update_reason_codes_by_desc_null_revcodes"
DoCmd.OpenQuery "Update_reason_codes_by_desc"
'************** If facility is OHSU remove non-billable items per contract**********
If Forms!frmClients!facility_ID = 102 Then
DoCmd.OpenQuery "qryOHSU_nonbillable"
End If
'**************************************************************
Forms!frmClients!frmISAmtsByRevenueCodes.Requery
Forms!frmClients!frmItemizedStmtTotals.Requery
DoCmd.DeleteObject acTable, "Sheet1"
DoCmd.SetWarnings (WarningsOn)
Else
MsgBox "UNABLE TO IMPORT IS RECORDS BECAUSE THE ITEMIZED" & vbCrLf & _
"STATEMENT'S TOTAL BILLED CHARGES ALREADY HAS A" & vbCrLf & _
"BALANCE > THAN ZERO INDICATING A PREVIOUS IMPORT", vbOKOnly, "UNABLE TO IMPORT IS RECORDS"
End If
Else
MsgBox "INACCURATE CLAIM REVIEW STATUS" & vbCrLf & _
"FOR ITEMIZED STATEMENT IMPORT", vbOKOnly, "INACCURATE CLAIM REVIEW STATUS"
End If
'RecalculateTotals
Exit Sub
Problems:
Err.Clear
Resume Next
End Sub

MSACCESS.EXE does not close when using POP-UP forms

Others have had issues with the MSACCESS.EXE process not closing (from Task Manager) when exiting their databases. Each of the posts I've read have had something to do with not properly closing recordset variables.
When I exit the database I'm working on, I notice the MSACCESS.EXE process moves from the "Apps" section to "Background Processes" in Win 10 Task Manager. This hung process continues to utilize RAM. I'm certain that I'm closing all recordset variables properly.
Through a lot of debugging, I figured out a simple way to replicate the problem:
Create two forms in a new Access database. Set the PopUp property to True for one of them and False for the other. Save the forms "PopUp" and "NoPopUp" and close the database.
Open Task Manager to view the processes running on your screen.
Open your Access database and open the NoPopUp form. Note the MSACCESS.EXE process under Apps.
Close your database. Note that MSACCESS.EXE is removed from your list of Processes (both under "Apps" and "Background Processes").
Now reopen your Access database and open form PopUp. Then close the database.
Note that the MSACCESS.EXE process moves from the "Apps" section to "Background Processes" and is still utilizing system memory.
Additional MSACCESS.EXE processes hang in Task Manager each time the database is closed after opening a form with its Pop-up property set to True.
My database uses a ton of Pop-up forms. How should I be closing my database so that these hung processes aren't stacking up? (I'm using Access 2013 in Windows 10.)
Thanks,
Sam
How are you closing your database now?
Can you change the command to call a function.
Then in that function call a routine that closes all open forms
You may have to add parameter to close without saving - depending on your results.
Function CloseAllOpenFrms()
On Error GoTo Error_Handler
Dim DbF As Access.Form
Dim DbO As Object
Set DbO = Application.Forms 'Collection of all the open forms
For Each DbF In DbO 'Loop all the forms
DoCmd.Close acForm, DbF.Name, acSaveNo
Next DbF
Error_Handler_Exit:
On Error Resume Next
Set DbF = Nothing
Set DbO = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: CloseAllOpenFrms" & vbCrLf & _
"Error Description: " & Err.Description, _
vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
From http://www.devhut.net/2015/02/17/ms-access-vba-close-all-open-forms/
Try this very basic example in a new sample database.
EDIT: Add a Sleep and DoEvents after every close form in case of caching/fast cpu getting ahead of code? Last attempt to fix weird issue.
In Module 1
Option Compare Database
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Function CloseAllOpenFrms()
On Error GoTo Error_Handler
Dim DbF As Access.Form
Dim DbO As Object
Set DbO = Application.Forms 'Collection of all the open forms
' Close all popups first
For Each DbF In DbO 'Loop all the forms
If DbF.PopUp Then
DoCmd.Close acForm, DbF.Name, acSaveNo
DoEvents
Sleep 1000
End If
Next DbF
' Close remaining forms
For Each DbF In DbO 'Loop all the forms
DoCmd.Close acForm, DbF.Name, acSaveNo
DoEvents
Sleep 1000
Next DbF
Application.Quit acQuitSaveNone
Error_Handler_Exit:
On Error Resume Next
Set DbF = Nothing
Set DbO = Nothing
Exit Function
Error_Handler:
MsgBox "Error closing : " & DbF.Name & vbCrLf & _
"Error Description: " & Err.Description, _
vbCritical, "Error closing form"
Resume Error_Handler_Exit
End Function
Create basic Form1 with two command buttons:
Command button Command1 (Caption= Open Popup Form)
Command button Command0 (Caption = Exit DB)
In Form1's form module paste text
'------------------------------------------------------------
' Command1_Click
'
'------------------------------------------------------------
Private Sub Command1_Click()
On Error GoTo Command1_Click_Err
CloseAllOpenFrms
Command1_Click_Exit:
Exit Sub
Command1_Click_Err:
MsgBox Error$
Resume Command1_Click_Exit
End Sub
'------------------------------------------------------------
' Command0_Click
'
'------------------------------------------------------------
Private Sub Command0_Click()
On Error GoTo Command0_Click_Err
DoCmd.OpenForm "Form2-popup", acNormal, "", "", , acWindowNormal
Command0_Click_Exit:
Exit Sub
Command0_Click_Err:
MsgBox Error$
Resume Command0_Click_Exit
End Sub
Create another form Form2-popup and set Popup property to true
Add command button Command1 with caption "Exit Form"
'------------------------------------------------------------
' Command1_Click
'
'------------------------------------------------------------
Private Sub Command1_Click()
On Error GoTo Command1_Click_Err
DoCmd.Close , ""
Command1_Click_Exit:
Exit Sub
Command1_Click_Err:
MsgBox Error$
Resume Command1_Click_Exit
End Sub

Make all fields mandatory to be filled in

This question is continued from here: Add user input to Excel table upon upload to Access database
Now that I have my fields connected to a table in my database, I want to make sure that everyone fills them in. Upon clicking the Import button, I want to check the fields (SANumber, SerialNumber, CustomerName, and LyoSize) to make sure it will be a 'valid upload'.
I have this code so far:
Function CheckInputs() As Boolean
If Me.SANumber.value Or Me.SerialNumber.value Or Me.CustomerName.value Or Me.LyoSize.value = Null Then
CheckInputs = True
Else
CheckInputs = False
End If
End Function
'Import MCL Files Code
Private Sub ImportMCL_Click()
On Error GoTo ErrorHandler
'disable ms access warnings
DoCmd.SetWarnings False
Call CheckInputs
If CheckInputs = True Then
MsgBox "All inputs must be entered!"
Exit Sub
Else
'load spreadsheet in .xls format
DoCmd.TransferSpreadsheet acImport, 8, "_MCL_UPLOAD", selectFile(), True
DoCmd.OpenQuery "UpdateMCL"
Call InsertInto_MASTER_UPLOAD
Call Delete_MCL_UPLOAD
MsgBox "MCL Imported Successfully!"
're-enable ms access warnings
DoCmd.SetWarnings True
End If
Exit Sub
ErrorHandler:
MsgBox "There was an Error: " & Err & ": " & Error(Err)
End Sub
It should work, but keeps on giving me the
ERROR: 13. Type Mismatch
You need to specifically check each field for null - you cannot do it this way:
If Me.SANumber.value Or Me.SerialNumber.value Or _
Me.CustomerName.value Or Me.LyoSize.value = Null Then
Something like
If IsNull(Me.SANumber) Or IsNull(SerialNumber) Or _
IsNull(Me.CustomerName) Or IsNull(Me.LyoSize) = Null Then
You should rename your function to something like "EmptyInputs" to make your code a little more self-documenting. "CheckInputs" is a little non-descriptive.
You CheckInputs() functions logic is incorrect. Or will return true if any one condition is meet. To get your desired result you can either ask does:
If Condition1 = true AND Condition2 = true AND ....
Otherwise you can ask If Condition1 = false OR Condition2 = false OR ....
Try this....
Function isFormValid() As Boolean
If isTextFieldInvalid(Me.SANumber) Or isTextFieldInvalid(Me.SerialNumber) Or isTextFieldInvalid(Me.CustomerName.Value) Or Me.LyoSize.Value = Null Then
isFormValid = False
Else
isFormValid = True
End If
End Function
Function isTextFieldInvalid(FieldControl) As Boolean
If Not IsNull(FieldControl) Then
If Len(Trim(FieldControl.Value)) Then
isFieldValid = True
End If
End If
End Function
'Import MCL Files Code
Private Sub ImportMCL_Click()
On Error GoTo ErrorHandler
'disable ms access warnings
DoCmd.SetWarnings False
If isFormValid Then
MsgBox "All inputs must be entered!"
Exit Sub
Else
'load spreadsheet in .xls format
DoCmd.TransferSpreadsheet acImport, 8, "_MCL_UPLOAD", selectFile(), True
DoCmd.OpenQuery "UpdateMCL"
Call InsertInto_MASTER_UPLOAD
Call Delete_MCL_UPLOAD
MsgBox "MCL Imported Successfully!"
're-enable ms access warnings
DoCmd.SetWarnings True
End If
Exit Sub
ErrorHandler:
MsgBox "There was an Error: " & Err & ": " & Error(Err)
End Sub
Also, if you're clearing out afterwards by going something like SANumber = "" then testing for Nulls might not work. I'd check for both nulls and blanks. This is a general template you could use.
Dim LResponse As Integer
If (Nz(Me.SANumber.Value) = "") Then
MsgBox "Please enter a SA Number.", vbCritical + vbOKOnly, "Error"
ElseIf (Nz(Me.SerialNumber.Value) = "") Then
MsgBox "Please enter a Serial Number.", vbCritical + vbOKOnly, "Error"
'All criteria met
Else
LResponse = MsgBox("Would you like to submit? ", vbQuestion + vbYesNo, "Question")
If LResponse = vbYes Then
'enter code here
ElseIf LResponse = vbNo Then
MsgBox ("Not submitted.")
End If
End If

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

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