Access 2010 email VBA - ms-access

I was wondering if anyone can help me.
I'm currently making an access 2010 DB which has the function to send tickets to other people.
I used the template provided by Access, which has the function to email the ticket to whom is it assigned to. Which is great. BUT I can't figure out how to get more than just the TITLE field in the body of the email.
I would like to have a body of text and a few more fields from the ticket if possible? Can anyone help me out?
I've converted the OnClick macro to VBA which I've pasted below.
How do I change this to do what I want?
Option Compare Database
'------------------------------------------------------------
' Macro1
'
'------------------------------------------------------------
Function Macro1()
On Error GoTo Macro1_Err
With CodeContextObject
On Error Resume Next
DoCmd.SendObject , "", "", DLookup("[E-mail Address]", "Contacts", "[ID]=" & Nz(.[Assigned To], 0)), "", "", "Duplicate for your attention", IIf(.Form.Description.TextFormat = 1, PlainText(.Title), .Title), True, ""
If (.MacroError.Number <> 0) Then
Beep
MsgBox .MacroError.Description, vbOKOnly, ""
End If
End With
Macro1_Exit:
Exit Function
Macro1_Err:
MsgBox Error$
Resume Macro1_Exit
End Function

I ones found this on the internet and used it for my ticketsystem: the varbody value contains the messagetext
Private Sub Command430_Click()
On Error GoTo ErrorHandler
Dim varName As Variant
Dim varCC As Variant
Dim varSubject As Variant
Dim varBody As Variant
varName = DLookup("[E-mail Address]"
'separate each email by a ','
varSubject = "Project " & [Forms]![Yourform]![Projectnr] & " contains a new ticket"
'Email subject
varBody = "Please pick up the following ticketnumer: " & [Forms]![Yourform]![Ticketnr]
'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File
ErrorHandler:
Select Case Err.Number
Case 2501
MsgBox ("No email send")
End Select
End Sub

Related

Error On click Button Docmd Report Error 3464

Hi Everyone How Are You I hope You Are Well.
I Am Working On A MS Access Application And Want Fetch Result From List Box With On Click Button
But I'm Facing A Error Data Type Mismatch In Criteria expression
Here is My Code On Click Button
Private Sub ViewBalance_Click()
'Dim listrpt As String
If IsNull(listrpt) Then
MsgBox "Please Select The Account Name", vbOKOnly, "Warning"
Exit Sub
End If
DoCmd.OpenReport "List All Parties Balance", acViewPreview, , "[Account ID] = """ & listrpt &
""""
Me.FilterOn = True
End Sub
And Here is My On Report Load Filter But This Filter Working Fine Above Code Give me Error
Report Load Code
Private Sub Report_Load()
DoCmd.Maximize
If MsgBox("Do You Want To Filter Available Balance Only?", vbYesNo + vbQuestion) = vbYes Then
Dim strFilter As String
strFilter = "[RQ]>0"
'verify that it looks good
Me.Filter = strFilter
Me.FilterOn = True
End If
End Sub
Report Name: List All Parties Balance
Query Name Where is Field Name: Account ID is: ListBalance
And listrpt Response Account ID = 60023
Please Anyone Give me A Support & Help Thanks in Advance

Splitting a report into separate emails with their individual reports

I am trying to send separate Employees a PDF/page of their section/report. The information is based on their EmployeeID (which is text not long number). So each person has their balance information on a page then there's a page break, and then next page shows the next person's details. With the code below, it does email each of the employees one page but it so happens to only email the first person's page to EVERYONE. Is it possible to somehow automate each week so that each user is emailed his/her individual page of the report?
Another error is that the email pop up one by one so I have to press send each time for over 200 people, and that the email seems to be sending to the email but then followed by #mailto:the email# for example email#email.com#mailto:email#email.com#
I just started Access and have been copying and scraping code off of places I have found online. Many thanks in advance, if you can assist!
Have a great day!
Private Sub cmdSendAll_Click()
Dim rsAccountNumber As DAO.Recordset
Dim strTo As Variant
Dim strSubject As String
Dim strMessageText As String
Set rsAccountNumber = CurrentDb.OpenRecordset("SELECT DISTINCT EmployeeID, [Email] FROM [queAutoUpdate]", dbOpenSnapshot)
Debug.Print strTo
With rsAccountNumber
Do Until .EOF
DoCmd.OpenReport "test", _
acViewPreview, _
WhereCondition:="EmployeeID = '" & !EmployeeID & "'", _
WindowMode:=acHidden
strTo = ![Email]
strSubject = "Updated Balance "
strMessageText = "Text Here"
DoCmd.SendObject ObjectType:=acSendReport, _
ObjectName:="test", _
OutputFormat:=acFormatPDF, _
To:=strTo, _
Subject:=strSubject, _
MESSAGETEXT:=strMessageText, _
EditMessage:=True
DoCmd.Close acReport, "Unaffirmed Report", acSaveNo
.MoveNext
Loop
.Close
End With
End Sub
Your opening a report called test and then closing another report called "Unaffirmed Report". You need to open and close the same report, in this case "test".
DoCmd.Close acReport, "test", acSaveNo. This should fix the employee data not updating, since the report remains open on the first employee.
To directly send the message you need change EditMessage:=True to EditMessage:=False.
Check the docs:
https://learn.microsoft.com/en-us/office/vba/api/access.docmd.sendobject
Also if you need to test this, set outlook in Offline mode, and run your code, check the messages in your Outbox to see if they're as expected. You can delete the messages from the Outbox to prevent them from being sent. Once you're finished with testing you can set Outlook back to Online Mode.
Regarding the email address issue, this comes automatically when using hyperlinks in your controls. You'll need to strip the extra part out with strTo = Left(![Email],InStr(![Email],"#")-1). Check your data if this will be valid for all email addresses. For a more advanced solution you can look at this post https://codekabinett.com/rdumps.php?Lang=2&targetDoc=access-hyperlink-data-type.
Code provided as reference, please see the post for the explanation.
'copied from https://codekabinett.com/rdumps.php?Lang=2&targetDoc=access-hyperlink-data-type
Public Function GetHyperlinkFullAddress(ByVal hyperlinkData As Variant, Optional ByVal removeMailto As Boolean) As Variant
Const SEPARATOR As String = "#"
Dim retVal As Variant
Dim tmpArr As Variant
If IsNull(hyperlinkData) Then
retVal = hyperlinkData
Else
If InStr(hyperlinkData, SEPARATOR) > 0 Then
' I append 4 separators at the end, so I don't have to worry about the
' lenght of the array returned by Split()
hyperlinkData = hyperlinkData & String(4, SEPARATOR)
tmpArr = Split(hyperlinkData, SEPARATOR)
If Len(tmpArr(1)) > 0 Then
retVal = tmpArr(1)
If Len(tmpArr(2)) > 0 Then
retVal = retVal & "#" & tmpArr(2)
End If
End If
Else
retVal = hyperlinkData
End If
If Left(retVal, 7) = "mailto:" Then
retVal = Mid(retVal, 8)
End If
End If
GetHyperlinkFullAddress = retVal
End Function
Consider using the MS Outlook object library to send emails. Whereas DoCmd.SendObject is a convenience handler, you control more of the process with initializing an Outlook application object and creating an Outlook email object setting all needed elements.
However, with this approach you need to first export your filtered report to PDF and then attach to email for final send. See inline comments for specific details.
Dim rsAccountNumber As DAO.Recordset
' CHECK Microsoft Outlook #.# Object Library UNDER Tools/References
Dim olApp As Outlook.Application, olEmail As Outlook.MailItem
Dim fileName As string, todayDate As String, strEmail As String
todayDate = Format(Date, "YYYY-MM-DD")
Set rsAccountNumber = CurrentDb.OpenRecordset("SELECT DISTINCT EmployeeID, [Email] FROM [queAutoUpdate]", dbOpenSnapshot)
Set olApp = New Outlook.Application
With rsAccountNumber
Do Until .EOF
' SETTING FILE NAME TO SAME PATH AS DATABASE (ADJUST AS NEEDED)
fileName = Application.CurrentProject.Path & "\Balance_Report_" & !EmployeeID & "_" & todayDate & ".pdf"
' OPEN AND EXPORT PDF TO FILE
DoCmd.OpenReport "test", acViewPreview, "EmployeeID = '" & !EmployeeID & "'"
' INTENTIONALLY LEAVE REPORT NAME BLANK FOR ABOVE FILTERED REPORT
DoCmd.OutputTo acReport, , acFormatPDF, fileName, False
DoCmd.Close acReport, "test"
' CREATE EMAIL OBJECT
strEmail = ![Email]
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
.Recipients.Add strEmail
.Subject = "Updated Balance"
.Body = "Text Here"
.Attachments.Add fileName ' ATTACH PDF REPORT
.Send ' SEND WITHOUT DISPLAY TO SCREEN
End With
Set olEmail = Nothing
.MoveNext
Loop
.Close
End With
MsgBox "All emails successfully sent!", vbInformation, "EMAIL STATUS"
Set rsAccountNumber = Nothing: Set olApp = Nothing

DoEvent() Returns 0 BUT Run-time Error 2585 This action can't be carried out while processing a form or report event

This code was running without a hitch, but now getting Error 2585.
I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.
I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.
Private Sub SaveData_Click()
Dim myForm As Form
Dim myTextBox As TextBox
Dim myDate As Date
Dim myResponse As Integer
If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then
myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
Forms!Ecoli_Data.SetFocus
Forms!Ecoli_Data!Collected_By.SetFocus
GoTo endOfSub
End If
If Me.Dirty Then Me.Dirty = False
myDate = Me.DateCollected.Value
Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String
Dim reportNumberText As String
reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText
Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)
Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()
Dim PauseTime, Start, Finish, TotalTime
PauseTime = 10 ' Set duration.
Start = Timer ' Set start time.
Do While Timer < Start + PauseTime
DoEvents ' Yield to other processes.
Loop
Finish = Timer ' Set end time.
TotalTime = Finish - Start ' Calculate total time.
myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)
myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")
If myResponse = vbYes Then
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
Error Generated By Line Above and occurs whether response Y or N to MsgBox.
DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
DoCmd.GoToRecord , , acNewRec
Else
DoCmd.Close acForm, "ECOLI_Data", acSaveYes
End If
Exit Sub
errorHandling:
If Err.Number = 2501 Then
myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
'Do nothing
Else
Debug.Print "Error Number: " & Err.Number & ": " & Err.Description
myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If
If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo
If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo
endOfSub:
End Sub
Any idea on what am I missing here? Thanks.
I can't replicate the problem, but the following might help:
I assume you run into troubles because you're closing and opening the form in the same operation. To avoid doing this, you can open up a second copy of the form, and close the form once the second copy is open. This avoids that issue.
To open a second copy of the form:
Public Myself As Form
Public Sub CopyMe()
Dim myCopy As New Form_CopyForm
myCopy.Visible = True
Set myCopy.Myself = myCopy
End Sub
(CopyForm is the form name)
To close a form that may or may not be a form created by this function
Public Sub CloseMe()
If Myself Is Nothing Then
DoCmd.Close acForm, Me.Name
Else
Set Myself = Nothing
End If
End Sub
More information on having multiple variants of the same form open can be found here, but my approach differs from the approach suggested here, and doesn't require a second object to hold references and manage copies.
This line of code
`DoCmd.Close acForm, "ECOLI_Data", acSaveYes`
doesn't save the record you are on, it just saves any changes to the form design.
You should probably use
If Me.Dirty Then Me.dirty = False
to force a save of the current record if any data has changed.

Docmd.acbrowsetoform where clause

Ok So here is my code. I think I'm close but when the frmCondition/Concerns Update form opens it ask for the strCBOProperty value. I know it is probably a syntax error, but I don't know what it is.
Private Sub btnLogin_Click()
Dim strCBOPassword As String
Dim strPassword As String
Dim strCBOProperty As String
Selectnull
strCBOProperty = Me.cboProperty.Column(0)
strCBOPassword = Me.cboProperty.Column(1)
strPassword = Me.txtPassword
If strCBOPassword = strPassword Then
MsgBox "Login Successful!"
DoCmd.BrowseTo acBrowseToForm, "frmCondition/Concerns Update", , "[Forms]![frmCondition/Concerns Update]!cbopropertyname = strCBOProperty"
Else
MsgBox "Invalid Password"
End If
End Sub
Private Sub Selectnull()
If IsNull(Me.cboProperty) Then
MsgBox "Please select a property", vbOKOnly
ElseIf IsNull(Me.txtPassword) Then
MsgBox "Please enter a password", vbOKOnly
End If
End Sub
I'd say you need something like this:
DoCmd.OpenForm "frmCondition", WhereCondition:="PropertyName='" & Me.cboProperty.Value & "'"
If not, tell us more about the contents of cboProperty and the data type of the property column in the conditions table.
If you have the value in a variable:
DoCmd.OpenForm "frmCondition", WhereCondition:="PropertyName='" & strCBOProperty & "'"
The variable must be outside of the string.
Using named parameters makes sure you get the parameter right. You have it on the FilterName position.

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