Embed HTML email attatchment in body from access query - html

I have a database. It has a form that sends an email, attaching query results to it (the attachment is an HTML document).
My VBA code for the form is:
Private Sub button_send_Click()
DoCmd.SendObject acSendQuery, Me!query_name, acFormatTXT, me!email_address, , , "Subject Line"
End Sub
I would not like my form to attach the query results. I need it to put the content from the attachment into the main body of the email instead.
Is there a way of doing this with VBA?

Use a function like this to list the output:
Public Function ListQuery() As String
Dim qdy As DAO.QueryDef
Dim rst As DAO.Recordset
Dim fld As DAO.Field
Dim List As String
Set qdy = CurrentDb.QueryDefs("YourQueryName")
qdy.Parameters(0).Value = Forms!NameOfYourForm!NameOfSomeTextbox.Value
qdy.Parameters(1).Value = Forms!NameOfYourForm!NameOfOtherTextbox.Value
Set rst = qdy.OpenRecordset()
If rst.RecordCount > 0 Then
While Not rst.EOF
For Each fld In rst.Fields
List = List & fld.Value & vbTab
Next
List = List & vbCrLf
rst.MoveNext
Wend
End If
rst.Close
Set fld = Nothing
Set rst = Nothing
Set qdy = Nothing
ListQuery = List
End Function
Then:
Dim MessageText As String
MessageText = ListQuery
DoCmd.SendObject acSendNoObject, , acFormatTXT, Me!email_address, , , "Subject Line", MessageText

Related

MS access - Application-Defined or Object-Defined Error while sending email

I have a code that is used to send emails using outlook from access. This code is throwing "Application-Defined or objected-Defined" error when the code is reaching .Recipient.Add line. This code works totally fine in my system but not in my colleague system. I have checked libraries and everything match but still the error is coming.
Private Sub Toggle182_Click()
On Error GoTo Err_Toggle182_Click
Dim BaCode As String
Dim lst As Control
Set lst = Me.name
Dim BillingMnth As String
BillingMnth = Format(Me.Billing_Month, "mmm")
Dim oItem As Variant
Dim iCount As Integer
Dim oApp As New Outlook.Application
Dim oEmail As Outlook.MailItem
Dim fileName As String
Dim sqry As String
Dim rs As DAO.Recordset
If lst.ItemsSelected.Count <> 0 Then
For Each oItem In lst.ItemsSelected
BaCode = lst.Column(0, oItem)
fileName = "My local path"
fileName = fileName & name & BillingMnth & ".xlsx"
sqry = "Select Distribution_List from details where name='" & name & "';"
Set rs = CurrentDb.OpenRecordset(sqry)
Set oEmail = oApp.CreateItem(olMailItem)
With oEmail
rs.MoveFirst
While Not rs.EOF
.Recipients.Add rs.Fields("Distribution_List")
rs.MoveNext
Wend
.Subject = "RTB"
.HTMLBody = "<HTML><BODY>Dear User <br><br> Please find the attached file. <br><br> Kindly do let us know in case of any concerns. <br> <br><br>Kind Regards, <br>company <br> </BODY></HTML>"
.Attachments.Add fileName
.Save
.Send
End With
iCount = iCount + 1
Next oItem
MsgBox "Email successfully sent!", vbInformation, "EMAIL STATUS"
Else
MsgBox "Please slect the name"
Exit Sub
End If
Err_Toggle182_Click:
'MsgBox Err.Description
End Sub
Possible that rs.Fields("Distribution_List") is null?
Try nz(rs.Fields("Distribution_List"),"") and see if it works.

Creating Event Procedure in MS Access

I have tried to create the event procedure, but It returns zero irrespective of my selection.
I have two tables, which are correctly joined, and below is the code that has an issue.
First, "MsgBox Me.Technology" is returning my selection value eg. Python, Java, but "MsgBox rs!ProjEmployeeID" is returning 0 all times. Help me troubleshoot the code. Thank you. I want it to return Project Employee ID like 1, 2, 3
Option Compare Database
Private Sub Technology_AfterUpdate()
MsgBox Me.Technology
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT ProjEmployeeID FROM Project WHERE Technologies = Trim('" & Forms!Form_employee_by_technologies!Technology & "')")
rs.AddNew
MsgBox rs!ProjEmployeeID
Dim strDocName As String
Dim strWhere As String
strDocName = "Technology"
strWhere = "[EmployeeID] =" & rs!ProjEmployeeID
DoCmd.OpenReport strDocName, acViewReport, , strWhere, acWindowNormal
End Sub

Access 2016 processing duplicate mail to Outlook via VBA

I have an Access 2016 database with tables that hold student data. I have managed to successfully send an email to each recipient using VBA-Outlook (the code works), however, it looks to have sent the the email to the same recipients multiple times (random duplicate of 1 to 4 emails per recipient).
I can confirm that there are no duplicate [E-mail Address] whatsoever contained within the Student table.
When I use .Display instead of .Send in my oEmailItem, there does not appear to be any duplicates. Perhaps I should include a waiting period of 1 second in the loop?
On Error Resume Next is used to bypass the null value returned by blank email fields; not everyone has an [E-mail Address] in this table
Why is this code sending random duplicate email to recipients?
Private Sub SendEmail_Click()
Dim rS As DAO.Recordset
Dim dbS As DAO.Database
Dim Filepath As String
Dim Folderpath As String
Dim oOutlook As Outlook.Application
Dim oEmailItem As MailItem
Dim myemail As String
Dim Subjectline As String
Subjectline$ = InputBox$("Please enter the subject line for this mailing.", _
"We need a Subject Line!")
Set dbS = CurrentDb()
Set rS = dbS.OpenRecordset("SELECT * FROM Students")
Do While Not rS.EOF
On Error Resume Next
myemail = rS![E-mail Address]
If oOutlook Is Nothing Then
Set oOutlook = New Outlook.Application
End If
'Set the email template
Set oEmailItem = oOutlook.CreateItemFromTemplate("C:\MailTemplate\Mail1.oft")
With oEmailItem
.To = [myemail]
.Subject = Subjectline$
.Send
End With
'End of emailing
rS.MoveNext
Loop
Set oEmailItem = Nothing
Set oOutlook = Nothing
Set rS = Nothing
Set dbS = Nothing
End Sub
Update:
Thanks HiPierr0t. Your answer showed me that I wasn't emptying the variable at the end of the loop; thus assigning the previously used [E-mail Address] when met with a null or blank email field.
I did have to keep
Set oEmailItem = oOutlook.CreateItemFromTemplate("C:\MailTemplate\Mail1.oft")
inside the loop however (strange, must be a MS thing).
I ended up removing On Error Resume Next as it does create more problems, and used
myemail = Nz(rS![Email Address], vbNullString)
to change any null or blank fields into "". That way, I don't need to empty to variable each time as the lookup changes it to "" if it's null anyway. The If..Else takes care of the rest.
Do While Not rS.EOF
'On Error Resume Next
myemail = Nz(rS![Email Address], vbNullString)
Set oEmailItem = oOutlook.CreateItemFromTemplate("C:\MailTemplate\Mail1.oft")
If myemail = "" Then
rS.MoveNext
Else
With oEmailItem
.To = [myemail]
.Subject = Subjectline$
.Display
End With
'End of my emailing report
rS.MoveNext
End If
Loop
On Error Resume Next tends to create more problems than it solves.
If no email exists, your code goes on. However your variable myemail is still filled with the previous email you sent an email to.
1- Make sure to empty your variable after the email is sent with myemail = "" or myemail = vbNullString.
2- Before sending the email, check that myemail is not empty with an If statement.
3- You may want to place your code below outside of the loop. It won't make a big difference but there is no need to process this part of code every time.
If oOutlook Is Nothing Then
Set oOutlook = New Outlook.Application
End If
'Set the email template
Set oEmailItem = oOutlook.CreateItemFromTemplate("C:\MailTemplate\Mail1.oft")
Please check if you’ve emptied the myemail before sending e-mail.
Also you need to add “rS.Close dbS.Close” after the Loop.
Here is complete code:
Private Sub SendEmail_Click()
Dim rS As DAO.Recordset
Dim dbS As DAO.Database
Dim Filepath As String
Dim Folderpath As String
Dim oOutlook As Outlook.Application
Dim oEmailItem As MailItem
Dim myemail As String
Dim Subjectline As String
Subjectline$ = InputBox$("Please enter the subject line for this mailing.", _
"We need a Subject Line!")
Set dbS = CurrentDb()
Set rS = dbS.OpenRecordset("SELECT * FROM Students")
Do While Not rS.EOF
On Error Resume Next
myemail = ""
myemail = rS![E-mail Address]
If oOutlook Is Nothing Then
Set oOutlook = New Outlook.Application
End If
'Set the email template
Set oEmailItem = oOutlook.CreateItemFromTemplate("C:\MailTemplate\Mail1.oft")
With oEmailItem
.To = [myemail]
.Subject = Subjectline$
.Send
End With
'End of emailing
rS.MoveNext
Loop
rS.Close
dbS.Close
Set oEmailItem = Nothing
Set oOutlook = Nothing
Set rS = Nothing
Set dbS = Nothing
End Sub

Parsing hyperlinks from Access VBA to Word template

I'm using VBA in Access 2010 form to populate a Word template with data from my tables.
What I can't achieve so far is inserting a hyperlink in the text.
To make things easier for me I'm inserting all the data into table in the template like this:
Private Sub button_Click()
On Error GoTo myError
Dim objWRD As Object 'Word.Application
Dim objDoc As Object 'Word.Document
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strRecords As String
'open a query and prepare the data'
Set db = CurrentDb()
Set qfd = db.QueryDefs("my_query")
Set rs = qfd.OpenRecordset()
'open a Word template'
Set objWRD = CreateObject("Word.Application")
objWRD.Visible = True
Set objDoc = objWRD.Documents.Add("path_to_my_document_template", , , True)
objWRD.ScreenUpdating = False
'insert records into template'
Dim i As Integer
i = 1
While Not rs.EOF
objDoc.Tables(i).Cell(2, 1).Range.Text = "" & rs("hyperlink")
objDoc.Tables(i).Cell(2, 2).Range.Text = "" & rs("description")
rs.MoveNext
i = i + 1
Wend
rs.Close
Set rs = Nothing
leave:
Exit Sub
myError:
MsgBox Error$
Resume Next
End Sub
Can anyone please help me to insert a working hyperlink to the template into rs("hyperlink") place?
Where you reference the table cell to hold the hyperlink, try this:
objDoc.Hyperlinks.add Anchor:=objDoc.tables(i).Cell(2, 1).Range, _
Address:=rs("hyperlink")
And to add additional text to the same cell (In this case I'm inserting "Text to Insert" prior to the hyperlink.
With objDoc.Tables(i).Cell(2, 1).Range
.Collapse Direction:=wdCollapseStart
.Text = "Text to Insert" & Chr(11)
End With
so your While Loop would look something like this:
Dim i As Integer
i = 1
While Not rs.EOF
objDoc.Hyperlinks.add Anchor:=objDoc.Tables(i).Cell(2, 1).Range, _
Address:=rs("hyperlink")
With objDoc.Tables(i).Cell(2, 1).Range
.Collapse Direction:=wdCollapseStart
.Text = "Text to Insert" & Chr(11)
End With
objDoc.Tables(i).Cell(2, 2).Range.Text = "" & rs("description")
rs.MoveNext
i = i + 1
Wend

Need to make a button create a record and attach a file

It's my first post here and I love how helpful people are on this site!
I have very little experience with vba in general so bear with me. And before you ask, I have spent a lot of time searching for my answer on this site as well as msdn with no luck.
I am designing a database for my work to keep track of employees and their contact info, training courses, and hiring documentation. I have hit a small road block with the hiring forms.
I have a form with employee's information and a subform that has a list of all their documentation. Each document is a record on a separate "documents" table that is pulled up with a query. The table has a field for the employee name, the type of document (resume et cetera) and the attachment itself. I have a dropdown box that has a list of document types. When I select an option from the combo box I would like it to create a new record in the "documents" table using the employee name from the current employee being shown, the document type selected from the combo box, then open the choose file dialogue.
Here is what I have so far
I have read microsoft's article on adding attachments which was helpful but doesn't tell me how to create a new record on another table.
https://support.office.com/en-us/article/Attach-files-and-graphics-to-the-records-in-your-database-bced3638-bfbc-43f0-822d-374bca2e6b40?CorrelationId=5332de93-8a42-4f76-bb47-c196bc1ce75b&ui=en-US&rs=en-US&ad=US
Any help would be greatly appreciated :)
Update: I've come a long way with the code, but i am getting stuck with inserting the attachment
Sub test()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset2
Dim rsA As DAO.Recordset2
Dim fld As DAO.Field2
'variables for file path
Dim sName
Dim f As Object
Dim strFile As String
Dim strFolder As String
Dim varItem As Variant
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("documents")
Set fld = rst("doc")
Set rsA = fld.Value
rst.AddNew
rst!inspector = "test"
rst.Update
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
If f.Show Then
For Each varItem In f.SelectedItems
strFile = Dir(varItem)
strFolder = Left(varItem, Len(varItem) - Len(strFile))
'MsgBox "Folder: " & strFolder & vbCrLf & _
"File: " & strFile
Next
End If
Set f = Nothing
sName = strFolder & strFile
rst.Edit
rst.AddNew
rsA("FileData").LoadFromFile sName ' <<<this is where i get stuck
rsA.Update
rst.Update
MsgBox ("done") 'test
End Sub
After banging my head against the desk for 2 days i finally have the code. I still need to make adjustments to fill in the other fields with the inspector name and the type of file, but it should be easy sailing from here. I was having the most trouble with creating a record and attaching a file
Sub test()
Dim dbs As DAO.Database
Dim tbl As DAO.Recordset2
Dim field As DAO.Recordset2
'variables for file path
Dim sName
Dim f As Object
Dim strFile As String
Dim strFolder As String
Dim varItem As Variant
Set db = CurrentDb
Set tbl = db.OpenRecordset("documents")
'get file path string
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For Each varItem In f.SelectedItems
strFile = Dir(varItem)
strFolder = Left(varItem, Len(varItem) - Len(strFile))
Next
End If
Set f = Nothing
sName = strFolder & strFile
tbl.Edit
tbl.AddNew 'add a new entry to the table
tbl!inspector = "test"
Set field = tbl.Fields("doc").Value
field.AddNew 'add an attachment to the record
field.Fields("FileData").LoadFromFile sName
field.Update
tbl.Update
End Sub