Error Handling- Looping script for email generation if network down - email

I've posted here before under a different account name and thanks all for previous help.
I have a spreadsheet which extracts information from a Data Historian, to generate a report on the status of the factory which is then automatically emailed out via Lotus Notes to recipients at fixed time intervals.
Sometimes there may be network issues affecting either the factory DCS, Data Historian (Aspen), or Lotus Notes. This gives a run time error when the script runs. Usually all that is required is to end the script, wait a period of time, recalculate the sheet, and then re-run the script.
Was hoping somebody could advise what code to add to achieve this. All I really need to know is what code to write and where to insert it to end the script in the event of a run-time error, and then to trigger another sub-routine in which I can add an application.wait and application.calculate before re-running the script. I need the script to end and run a separate sub as it causes issues with multiple scheduled events otherwise which then ultimately sends out multiple emails.
I've marked the part of the script that usually fails.
Sub Macro6()
Windows("Silo report 2 hourly.xlsm").Activate
' Range("A1").Select
'Calculate all workbooks
Application.Calculate
'Set up the objects required for Automation into lotus notes
Dim Maildb As Object 'The mail database
Dim UserName As String 'The current users notes name
Dim MailDbName As String 'THe current users notes mail database name
Dim MailDoc As Object 'The mail document itself
Dim AttachME As Object 'The attachment richtextfile object
Dim Session As Object 'The notes session
Dim EmbedObj As Object 'The embedded object (Attachment)
'Start a session to notes
Set Session = CreateObject("Notes.NotesSession")
'Next line only works with 5.x and above. Replace password with your password
'Get the sessions username and then calculate the mail file name
'You may or may not need this as for MailDBname with some systems you
'can pass an empty string or using above password you can use other mailboxes.
UserName = Session.UserName
MailDbName = Left$(UserName, 1) & Right$(UserName, (Len(UserName) - InStr(1, UserName, " "))) & ".nsf"
'Open the mail database in notes
Set Maildb = Session.GETDATABASE("", MailDbName)
If Maildb.IsOpen = True Then
'Already open for mail
Else
Maildb.OPENMAIL
End If
'Set up the new mail document
Set MailDoc = Maildb.CreateDocument
MailDoc.Form = "Memo"
vaRecipient = VBA.Array("xxx.xxx#xxx.com", "yyy.yyy#yyy.com", "zzz.zzz#zzz.com")
MailDoc.SendTo = vaRecipient
MailDoc.Subject = Range("B1").Value
Set workspace = CreateObject("Notes.NotesUIWorkspace")
'**THE RUNTIME ERROR USUALLY OCCURS WITHIN THE NEXT 5 LINES OF SCRIPT**
Dim notesUIDoc As Object
Set notesUIDoc = workspace.EditDocument(True, MailDoc)
Call notesUIDoc.GOTOFIELD("Body")
Call notesUIDoc.FieldClear("Body")
Call notesUIDoc.FieldAppendText("Body", Range("B9").Value & vbCrLf & vbCrLf & Range("b10").Value & Range("I10").Value & Range("D10").Value & vbCrLf & Range("b11").Value & Range("I11").Value & Range("D11").Value & vbCrLf & Range("b12").Value & Range("I12").Value & Range("D12").Value & vbCrLf & vbCrLf & Range("b13").Value & Range("I13").Value & Range("D13").Value & vbCrLf & vbCrLf & Range("b14").Value & Range("C14").Value & Range("D14").Value & vbCrLf & vbCrLf & Range("b15").Value & Range("I15").Value & Range("D15").Value & vbCrLf)
notesUIDoc.Send
notesUIDoc.Close
MailDoc.PostedDate = Now() 'Gets the mail to appear in the sent items folder
'MailDoc.Send 0, vaRecipient
'Clean Up
Set Maildb = Nothing
Set MailDoc = Nothing
Set AttachME = Nothing
Set Session = Nothing
Set EmbedObj = Nothing
End Sub

In LotusScript as well as in Visual Basic / VBA the error handling works exact the same. At the beginning of your Script you define where to go if an error occurs:
On Error Goto ErrorHandler
Place a Jump- Mark above the line, where you want to start over, when the error occurs:
TryAgain:
At the very end of your sub you define the errorhandler itself:
EndSub:
'- prohibit that error handler is called without an error
Exit Sub
ErrorHandler:
'- here you can react on the error, e.g. check for the err (Error number)
If err = NumberOfErrorThatOccursWhenNetworkErrorOccurs then
'- wait some time to give the network time to recover
Sleep x '- put in x as best for your problem
'- jump back
Resume TryAgain
Else
'- another error occured: inform user
Messagebox err & ", " & Error & " in line " & Erl
'- now jump to the end of the sub
Resume EndSub
End If
Of course this is a minimal errorhandling, and probably you would not want to jump around without further checks, but the idea should be clear with this example.
Just one more thing from the comments: you don't need the ui- stuff at all! Just omit it, as it is totally unneccessary and makes your code unstable.
Replace the whole paragraph starting with Set workspace... ending with notesUIDoc.close with two lines of code:
Call Maildoc.ReplaceItemValue( "Body", Range("B9").Value ..... )
Call Maildoc.Send( False )
Then you don't have to take care if something goes wrong - the document will just be discarded when the code runs again or ends, and it will be much more stable than handling ui windows and the screen will not flicker...

Related

Why is Access form giving me the error message "A column number has been specified more than once in the order list"? The related queries open fine

I'm working on an Access database with a SQL Server back end. Some times when I open a particular form, I get an Error 3146 "Column has been specified more than once in the order by list."
There are several possible queries that might feed into this form but I checked and ran them all individually and they run fine, so it's something in the form but I'm not sure. Below is a screen shot of the Data Properties window. My hypothesis is that "Order By" property (which I did not populate manually) is not being cleared out when the form closes, and thus when the form is re-opened, that in effect puts in the same columns twice.
I can temporarily solve the problem by opening up the form and clearing those Filter and Order By fields. That solves it for a while but intermittently it will happen again so there's probably one other thing I'm overlooking. I put in code in the Form close event to set the orderby="" but even that doesn't totally solve it.
Here is the code that opens the form from the main menu (frmProdSched is the form in question)
Private Function OpenProdSched(RunQuery, RunCaption)
DoCmd.OpenForm "frmProdSched", , RunQuery, "", , acNormal
Forms!frmProdSched.Caption = RunCaption
gScheduleRptQry = RunQuery
Me.Refresh
End Function
and then the code that is in the Form_Current event
Private Sub Form_Current()
On Error Resume Next
Dim strForm As String
Dim strForm1 As String
Dim strWhere As String
strForm = "frmSubmittalStatus"
strForm1 = "frmProdSched"
strWhere = "StatusJobno = " & Me.JOBNO & ""
If IsLoaded(strForm) Then
If Forms(strForm).Filter = strWhere Then
Forms(strForm1).SetFocus
Else
DoCmd.Close acForm, strForm
DoCmd.OpenForm FormName:=strForm, WhereCondition:=strWhere
Forms(strForm1).SetFocus
End If
End If
End Sub
I tried adding this code to the Form Close event and it seemed to work most of the time but it still intermittently happens
Private Sub Form_Close()
Me.Filter = ""
Me.OrderBy = ""
End Sub
I'm not sure what to check next. Any ideas?

Deleting the first record on continuous form in MS Access 2013

I have a "remove" button on a continuous form that performs the following SQL when clicked:
Dim strSQL As String
strSQL = "Delete SLIDE_NAME, COB_TITLE, COB_ID, COB_CATEGORY " _
& "FROM tbl_SLIDE_LIST " _
& "WHERE SLIDE_NAME='" & strSlideName & "' AND COB_TITLE='" & strCOB_TITLE & "';"
CurrentDb.Execute (strSQL)
The button sits on the continuous form like so:
There must be some sort of initialization I need to perform to make this work properly -
I can delete the 2nd and 3rd records with no problem, but if I click the "remove" button on the first record, the subform becomes blank, as if I deleted all records - (which is not actually the case). Then if I reselect the "Test Slide" to look at what actually happened, I receive the error "The data has been changed" Another user edited this record and saved the changes before you attempted to save your changes.
What is happening here and what do I need to do to make this work correctly?
If you delete a record with SQL, the form doesn't know about it. You need to do Me.Requery afterwards.
Much simpler would be to run DoCmd.RunCommand acCmdDeleteRecord.
From http://access.mvps.org/access/RunCommand/codeex/50-223.htm :
'Code from Microsoft Knowledge Base Adapted by Terry Wickenden
Private Sub cmdDelete_Click()
On Error GoTo Err_cmdDelete_Click
DoCmd.SetWarnings False
If MsgBox("Confirm deletion of the record?", vbQuestion + vbYesNo + vbDefaultButton2, "Delete?") = vbYes Then
DoCmd.RunCommand acCmdSelectRecord ' I think this isn't needed
DoCmd.RunCommand acCmdDeleteRecord
End If
Exit_cmdDelete_Click:
DoCmd.SetWarnings True
Exit Sub
Err_cmdDelete_Click:
MsgBox Err.Description
Resume Exit_cmdDelete_Click
End Sub

How to refresh/requery report in access VBA before auto-exporting it on database launch

I searched thoroughly and tried many different solutions, but I can't seem to get it to work, even though it shouldn't be that difficult.
I have an access database which automatically sends reports by e-mail, every monday morning, when the database is opened. The problem is I can't get the reports to show the most recent data in the charts. The procedure is as follows (with Report1 as example)
(Users open a .accdr version of the database)
Upon opening this code runs when the head form loads (form_load event):
If Weekday(Now(), 2) = 1 Then
If Forms![Head Form]![Once subform].Form![ID] = 0 Then
DoCmd.OpenQuery "UpdateOnce1", acViewNormal, acEdit
DoCmd.SetWarnings False
DoCmd.OpenReport "Report1", acViewPreview
DoCmd.RunSavedImportExport "Export-Report 1"
Dim strSql
Dim db As Database
Set db = CurrentDb()
Dim Outlook
Dim rng
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "number of mail adresses"
.CC = ""
.BCC = ""
.Subject = "Report 1"
.HTMLBody = ""
.Attachments.Add ("T:\.....\Report1.pdf")
.Send
End With
DoCmd.Close acReport, "Report1"
End If
End If
So if it is monday, and the code hasn't run yet, Report 1 is openend, exported to PDF, added as an attachment and then mailed via outlook.
As you can see I currently tried opening the reports before calling the code to mail the pdf, in hopes of refreshing it before it exports. But it doesn't seem to be working unfortunately, because the report doesn't show the most recent data.
Any ideas on how I can refresh/requery the report before it is exported & mailed? Much appreciated.
Tim
One way around it is a make table with the most recent data you want when your criteria is met (monday, not been ran yet) and base the report off that, then once you have exported the report delete the temp table with your data. This also prevents users pissing around with your queries/set up etc.
a bit like
dim ssql as string
sSql = "Select yourFields from yourTable INTO tmpTblRpt"
currentdb.execute(ssql)
'set the rpt to be based off tmptblRpt here
then set warnings off docmd.deleteObject actable, "tmpTblRpt" then warnings back on

ACCESS 2003: Checking to see if record exists BEFORE UPDATE and then display message THEN OPEN existing record

Working on this for awhile now and i'm getting runtime error 2501
i'm trying to pull up a record after the message box appears stating that a duplicate has been found and upon clicking "OK" pulls up the record.
i have been tinkering with the DoCmd.FindRecord, DoCmd.GoToRecord, and DoCmd.OpenForm methods to no avail.
Any help would be greatly appreciated.
Thanks in advance.
Private Sub MRN_BeforeUpdate(Cancel As Integer)
Dim Answer As Variant
Answer = DLookup("[MRN]", "Requests Processed", "[MRN] = '" & Me.MRN & "'")
If Not IsNull(Answer) Then
MsgBox "Existing MRN found" & ": " & MRN.Text & vbCrLf & vbCrLf & "Please SEARCH and EDIT on EXISTING Record.", vbCritical + vbOKOnly + vbDefaultButton1, "EXISTING MRN FOUND"
Cancel = True
Me.MRN.Undo
Else:
End If
DoCmd.OpenForm "Requests Processed", , , Answer
End Sub
From the help topic, the OpenForm method's WhereCondition option is "A string expression that's a valid SQL WHERE clause without the word WHERE."
Try OpenForm this way ...
DoCmd.OpenForm "Requests Processed", , , "[MRN] = '" & Answer & "'"
It looks to me like that could work. However it seems you can use the same string for both your DLookup Criteria option and your OpenForm WhereCondition. If that's true create one string variable (eg strWhere) and use it in both places.

Enable Save button on different tabs when a form opens

I have a tab control on a form, and a couple different tabs have save buttons on them. Once the user saves data (via SQL statements in VBA), I set the .enabled = false so that they cannot use this button again until moving to a brand new record (which is a button click on the overall form).
so when my form open i was going to reference a sub that enabled all these save buttons because the open event would mean new record. though i get an error that says it either does not exist, or is closed.
any ideas?
thanks
EDIT:
Sub Example()
error handling
Dim db as dao.database
dim rs as dao.recordset
dim sql as string
SQL = "INSERT INTO tblMain (Name, Address, CITY) VALUES ("
if not isnull (me.name) then
sql = sql & """" & me.name & ""","
else
sql = sql & " NULL,"
end if
if not insull(me.adress) then
sql = sql & " """ & me.address & ""","
else
sql = sql & " NULL,"
end if
if not isnull(me.city) then
sql = sql & " """ & me.city & ""","
else
sql = sql & " NULL,"
end if
'debug.print(sql)
set db = currentdb
db.execute (sql)
MsgBox "Changes were successfully saved"
me.MyTabCtl.Pages.Item("SecondPage").setfocus
me.cmdSaveInfo.enabled = false
and then on then the cmdSave needs to get re enabled on a new record (which by the way, this form is unbound), so it all happens when the form is re-opened. I tried this:
Sub Form_Open()
me.cmdSaveInfo.enabled = true
End Sub
and this is where I get the error stated above. So this is also not the tab that has focus when the form opens. Is that why I get this error? I cannot enable or disable a control when the tab is not showing?
You cannot use the form open event to manipulate controls, they have not been initiated at that stage. Use the form load event.
It should never be necessary to set focus to a tab, or even to reference it when working with a control. You will notice that controls must have names unique to the form, and adding a tab does not change this.
I suggest you set some form-level variables: booBtn_1_enabled as Boolean, booBtn_2_enabled as Boolean. Set these to T or F as needed; obviously, all T when the form is opened. Pick a form event (possibly the Current event, but preferably one that is triggered less often) that reviews these variables and sets the controls accordingly:
Me.btnBtn_1.Enabled = booBtn_1_enabled
Me.Repaint
Something like that, but obviously Me.btnBtn_1 may need a more complicated reference.