I'm using the following code to loop through records in a test table and output the results to an outlook email (see below). When I run the code as a Private Sub from Access based on a button click event, it works correctly (opens up outlook and sends the email). But when I try to use task scheduler to run the code through a Macro, it doesn't work. It looks like the task scheduler opened an instance of the database, but it's locked, so I can't close it (It won't let me delete the .laccdb file). The error message when I try to delete is: "This action can't be completed because the file is open in MSACCESS.EXE".
Public Function output_order_list()
Dim olApp As New Outlook.Application
Dim olMailItem As Outlook.MailItem
Dim rstOpenTrip As Recordset
Dim strSubject, strBody, strAddresses As String
Dim db As Database
Dim strSQL As String
Dim blnNewInstance As Boolean
Set olMailItem = olApp.CreateItem(0)
Set db = CurrentDb()
strSQL = "SELECT * FROM Table1;"
Set rstOpenTrip = db.OpenRecordset(strSQL, dbOpenDynaset)
strAddresses = "someone@gmail.com"
If Not rstOpenTrip.EOF Then
strBody = "blah blah blah" & vbCrLf & vbCrLf
strBody = strBody & "Field1 Field2" & vbCrLf
strBody = strBody & "==================================" & vbCrLf
rstOpenTrip.MoveFirst
Do While Not rstOpenTrip.EOF
strBody = strBody & rstOpenTrip("Field1") & Chr(9) & _
rstOpenTrip("Field2") & Chr(9) & vbCrLf
rstOpenTrip.MoveNext
Loop
End If
With olMailItem
.To = strAddresses
.Subject = "Here's my report"
.Body = strBody
.Display
.Send
End With
Set olMailItem = Nothing
Set olApp = Nothing
Application.Quit
End Function
Public Function output_order_list()
Dim olApp As New Outlook.Application
Dim olMailItem As Outlook.MailItem
Dim rstOpenTrip As Recordset
Dim strSubject, strBody, strAddresses As String
Dim db As Database
Dim strSQL As String
Dim blnNewInstance As Boolean
Set olMailItem = olApp.CreateItem(0)
Set db = CurrentDb()
strSQL = "SELECT * FROM Table1;"
Set rstOpenTrip = db.OpenRecordset(strSQL, dbOpenDynaset)
strAddresses = "someone@gmail.com"
If Not rstOpenTrip.EOF Then
strBody = "blah blah blah" & vbCrLf & vbCrLf
strBody = strBody & "Field1 Field2" & vbCrLf
strBody = strBody & "==================================" & vbCrLf
rstOpenTrip.MoveFirst
Do While Not rstOpenTrip.EOF
strBody = strBody & rstOpenTrip("Field1") & Chr(9) & _
rstOpenTrip("Field2") & Chr(9) & vbCrLf
rstOpenTrip.MoveNext
Loop
End If
With olMailItem
.To = strAddresses
.Subject = "Here's my report"
.Body = strBody
.Display
.Send
End With
Set olMailItem = Nothing
Set olApp = Nothing
Application.Quit
End Function