MS Access - VBA: Sending Email Using Email Addresses in Tables - vba

Using MS Access VBA. Setup is as follows:
tblUsers contains UserID, UserName, UserSecurityLevel, UserEmail
tblStewards contains AreaID, AreaName, Stewards where Stewards is set to be a Combo Box from a Lookup Query "SELECT tblUsers.ID, tblUsers.UserName FROM tblUsers" and I allow multiple values (e.g., each area has multiple stewards); the Stewards field has a data type of short text
frmStewardRequest has Record Source tblStewards and is designed for a user to request that the area stewards add a new item; it contains cmbAreaName, txtStewards which autopopulates based on cmbAreaName with Control Source Stewards, some open text fields for supplying the requested item, and a btnSubmitRequest
for btnSubmitRequest, I have an On Click event that generates an email to the area stewards using this VBA code:
Dim strEmailTo As String
Dim strTxtBody As String
strEmailTo = DLookup("[UserEmail]", "tblUsers", "ID = " & Me.txtSteward)
strTxtBody = "I need a new item in " & Me.cmbAreaName & "..."
DoCmd.SendObject , , acFormatTXT, strEmailTo, , , "New Item Request", strTxtBody, False
There is a problem with getting the email addresses for the area stewards: it doesn't seem this is a string. How can I get the email addresses so this will send properly? (Less important question, is there a way to prevent the pop-up box to Accept the risk of sending this email?)

This is how I do it.
Option Compare Database
Option Explicit
' This database and all the code therein is © 1999-2002 Arvin Meyer arvinm#datastrat.com
' You are free to use this code and this database in an application
' as long as you do not publish it without the author's permission.
' Additionally, you are required to include this copyright notice in the application.
Private Sub Form_Open(Cancel As Integer)
On Error GoTo Err_OF
Dim db As Database
Dim i As Integer
Dim contr As Container
Dim strRptList As String
Dim strRptName As String
Dim Length As Integer
Set db = CurrentDb()
Set contr = db.Containers("Reports")
strRptList = ""
For i = 0 To contr.Documents.Count - 1
strRptName = contr.Documents(i).name
If strRptList <> "" Then strRptList = strRptList & "; "
Length = Len(strRptName)
strRptList = strRptList & strRptName
Next i
Me!lstRpt.RowSource = strRptList
Exit_OF:
Exit Sub
Err_OF:
MsgBox Err & " " & Error, , "Report Open"
Resume Exit_OF
End Sub
Private Sub cmdEmail_Click()
On Error GoTo Err_cmdEmail_Click
Dim strDocName As String
Dim strEmail As String
Dim strMailSubject As String
Dim strMsg As String
strDocName = Me.lstRpt
strEmail = Me.txtSelected & vbNullString
strMailSubject = Me.txtMailSubject & vbNullString
strMsg = Me.txtMsg & vbNullString & vbCrLf & vbCrLf & "Your Name" & _
vbCrLf & "MailTo:youremail#nowhere.com"
DoCmd.SendObject objecttype:=acSendReport, _
ObjectName:=strDocName, outputformat:=acFormatHTML, _
To:=strEmail, Subject:=strMailSubject, MessageText:=strMsg
Exit_cmdEmail_Click:
Exit Sub
Err_cmdEmail_Click:
MsgBox Err.Description
Resume Exit_cmdEmail_Click
End Sub
Private Sub Label15_Click()
Dim hplMail As String
hplMail = "#MailTo:email_senate#datastrat.com#"
Application.FollowHyperlink HyperlinkPart(hplMail, acAddress)
End Sub
Private Sub lstRpt_Click()
Me.cmdEmail.Enabled = True
End Sub
Private Sub lstMailTo_Click()
Dim varItem As Variant
Dim strList As String
With Me!lstMailTo
If .MultiSelect = 0 Then
Me!txtSelected = .Value
Else
For Each varItem In .ItemsSelected
strList = strList & .Column(0, varItem) & ";"
Next varItem
strList = Left$(strList, Len(strList) - 1)
Me!txtSelected = strList
End If
End With
End Sub

Table tblStewards Combo Box lookup query SELECT tblUsers.ID, tblUsers.UserName FROM tblUsers needs to be fixed since there is no ID but UserID
Have used the Split function to check for multiple Steward values and then get their email id using Dlookup
I prefer using MultiValued fields especially when lookup list is not huge (nothing wrong to use).
Dim strStewards As Variant
Dim i As Long
Dim strEmailTo As String
Dim strTxtBody As String
strStewards = Split(Me.txtSteward, ",")
For i = LBound(strStewards) To UBound(strStewards)
strEmailTo = strEmailTo & ";" & Nz(DLookup("[UserEmail]", "tblUsers", "UserID=" & strStewards(i)), "")
Next
strTxtBody = "I need a new item in " & Me.cmbAreaName & "..."
DoCmd.SendObject , , acFormatTXT, strEmailTo, , , "New Item Request", strTxtBody, False

Related

Searching Multiple Items Using Combo box and List box for a ms access form

I have a split form with a combo box (named cmb_KostenstellenAll) that shows cost centers. I can filter my form with cost center from this combo box (My form comes from a query called qryFürFormular).I added a list box (named lbx_KsAll) to make multiple selections when applying the filter. If is selected in the combo box, the list box becomes visible and I can select more than one cost center. Codes to do this:
Private Sub cmb_KostenstellenAll_AfterUpdate()
If Me.cmb_KostenstellenAll = "<Multiple selection>" Then
Me.lbx_KsAll.Visible = True
else
Me.lbx_KsAll.Visible = False
Me.Requery
End If
end sub
Private Sub lbx_KsAll_AfterUpdate()
Dim varItem As Variant
Dim strCriteria As String
Dim TempMultiState As TempVar
For Each varItem In Me!lbx_KsAll.ItemsSelected
strCriteria = strCriteria & "," & Me!lbx_KsAll.ItemData(varItem) & ""
Next varItem
If Len(strCriteria) = 0 Then
Exit Sub
Else
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
TempVars!TempMultiState = strCriteria
MsgBox (TempVars!TempMultiState)
End If
End Sub
However, when I click the search button (named cmd_Search) with two selected cost center (called Sondermachninenbau and Testing), I get an error: syntax error (missing operator) in query expression '([Kostenstellen_NEU] in (Sondermachninenbau,Testing))'.
I wrote this code:
Private Sub cmd_Suchen_Click()
Call Search
End Sub
Sub Search()
Dim myKS, strSQL, strCriteria As String
If IsNull(Me.cmb_KostenstellenAll) Then
ElseIf Me.cmb_KostenstellenAll = "<Multiple selection>" Then
strCriteria = "[Kostenstellen_NEU] in (" & TempVars!TempMultiState & ")"
MsgBox (TempVars!TempMultiState)
Else
myKS = "[Kostenstellen_NEU]='" & Me.cmb_KostenstellenAll & "'"
strCriteria = myKS
End If
strSQL = "select * from qryFürFormular where (" & strCriteria & ")"
Me.RecordSource = strSQL
Me.Requery
End Sub
Me.RecordSource = strSQL is highligted.
In the example where I got the code like this(He had a table called Customers and
then created a form and added a subform with record source Customers) :
End If
strSQL = "select * from customers where (" & strCriteria & ")"
Me.customers_subform.Form.RecordSource = strSQL
Me.Customers_subform.FormRequery
End Sub

VBA Error Messages interspersed with running as planned

I have a Macro that works inconsistently and it is unable to run without an error occuring at some stage. It works without any problem for days but then doesn't, seemingly without reason. I change nothing, do not do anything different and am curious as to the fickleness of VBA/macros only having been dealing with them for some weeks now. An error is generated in those instances that it doesn't run as expected.
Error :object doesn't support this property or method
--despite the option of caption being generated on the insertion of .
Sub SnoozedReminders()
Dim oReminder As Reminder
Dim oReminders As Outlook.Reminders
Dim RemItems As String
Set oReminders = Outlook.Reminders
For Each oReminder In oReminders
If (oReminder.OriginalReminderDate <> oReminder.NextReminderDate)
Then
RemItems = RemItems & oReminder.Caption & vbCrLf & _
"Original Reminder time: " & oReminder.OriginalReminderDate & vbCrLf
& _
"Snoozed to: " & oReminder.NextReminderDate & vbCrLf _
& vbCrLf
End If
Next oReminder
Set oMail = Application.CreateItem(olMailItem)
oMail.Subject = "Generated on " & Now
oMail.Body = RemItems
oMail.Display
End Sub
In the code you are trying to set a type to the object:
Set oReminders = Outlook.Reminders
Instead, you need to use the following code which uses the Reminders property of the Outlook Application class:
Set oReminders = Application.Reminders
For example, the following code gets the Reminders collection and displays the captions of all reminders in the collection. If no current reminders are available, a message is displayed to the user.
Sub ViewReminderInfo()
'Lists reminder caption information
Dim objRem As Outlook.Reminder
Dim objRems As Outlook.Reminders
Dim strTitle As String
Dim strReport As String
Set objRems = Application.Reminders
strTitle = "Current Reminders:"
strReport = ""
'If there are reminders, display message
If Application.Reminders.Count <> 0 Then
For Each objRem In objRems
'Add information to string
strReport = strReport & objRem.Caption & vbCr
Next objRem
'Display report in dialog
MsgBox strTitle & vbCr & vbCr & strReport
Else
MsgBox "There are no reminders in the collection."
End If
End Sub

ListBox Multiselect in MS Access

I have created a form to get all the field header names, but I'm unable to select multiple fields. Attached is for your reference.
Following is the code used to get the Headers from the Master Table:
Private Sub Form_Load()
'Call GetColumnNameFromIndex
'Call List4_Click
Dim rst As New ADODB.Recordset
rst.Open "SELECT * FROM Master_DataBase", CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
' Note: adOpenForwardOnly and adLockReadOnly are the default values '
' for the CursorType and LockType arguments, so they are optional here '
' and are shown only for completeness '
Dim ii As Integer
Dim ss As String
For ii = 0 To rst.Fields.Count - 1
ss = ss & "," & rst.Fields(ii).Name
Next ii
Me.List4.RowSource = ss
Debug.Print ss
Me.Requery
End Sub
Set your properties to Simple or Extended.
Sample VBA code may look like this.
Option Compare Database
Private Sub cmdOpenQuery_Click()
On Error GoTo Err_cmdOpenQuery_Click
Dim MyDB As DAO.Database
Dim qdef As DAO.QueryDef
Dim i As Integer
Dim strSQL As String
Dim strWhere As String
Dim strIN As String
Dim flgSelectAll As Boolean
Dim varItem As Variant
Set MyDB = CurrentDb()
strSQL = "SELECT * FROM tblCompanies"
'Build the IN string by looping through the listbox
For i = 0 To lstCounties.ListCount - 1
If lstCounties.Selected(i) Then
If lstCounties.Column(0, i) = "All" Then
flgSelectAll = True
End If
strIN = strIN & "'" & lstCounties.Column(0, i) & "',"
End If
Next i
'Create the WHERE string, and strip off the last comma of the IN string
strWhere = " WHERE [strCompanyCountries] in (" & Left(strIN, Len(strIN) - 1) & ")"
'If "All" was selected in the listbox, don't add the WHERE condition
If Not flgSelectAll Then
strSQL = strSQL & strWhere
End If
MyDB.QueryDefs.Delete "qryCompanyCounties"
Set qdef = MyDB.CreateQueryDef("qryCompanyCounties", strSQL)
'Open the query, built using the IN clause to set the criteria
DoCmd.OpenQuery "qryCompanyCounties", acViewNormal
'Clear listbox selection after running query
For Each varItem In Me.lstCounties.ItemsSelected
Me.lstCounties.Selected(varItem) = False
Next varItem
Exit_cmdOpenQuery_Click:
Exit Sub
Err_cmdOpenQuery_Click:
If Err.Number = 5 Then
MsgBox "You must make a selection(s) from the list", , "Selection Required !"
Resume Exit_cmdOpenQuery_Click
Else
'Write out the error and exit the sub
MsgBox Err.Description
Resume Exit_cmdOpenQuery_Click
End If
End Sub
Please customize to your specific needs.

multi-combo box search with VBA

I am currently having this issue of my search not working correctly. The idea is to have the user click on different fields and have them assigned to textboxes and then be searched against. Above is what the UI currently looks like in the form and the code is attached below. For example, when I pick firstName as the field 1 and Title as field 2, enter the text "joe" into field 1 into
and "student" into the respective text boxes and then hit search, it shows all of the student results instead of that single row of data in the table. I am thinking this is could be an issue of the combo boxes not being synchronized, where let's say if cbo1 and cbo2 declare fields, then those repsective text fields become filtered. cboField, cboField2 and cboField3 are all combo boxes and command_21 is a search button and command_28 is a show all records. I am very new to this still and am not entirely sure. Any help is appreciated. Thanks in advance
Option Compare Database
Private Sub cboField_Enter()
Dim oRS As DAO.Recordset, i As Integer
If Me.Form.FilterOn = True Then DoCmd.ShowAllRecords
Set oRS = Me.RecordsetClone
cboField.RowSourceType = "Value List"
cboField.RowSource = ""
For i = 0 To oRS.Fields.Count - 1
If oRS.Fields(i).Type = dbText Then cboField.AddItem oRS.Fields(i).Name
Next i
End Sub
Private Sub cboField2_Enter()
Dim rs As DAO.Recordset, i As Integer
If Me.Form.FilterOn = True Then DoCmd.ShowAllRecords
Set rs = Me.RecordsetClone
cboField2.RowSourceType = "Value List"
cboField2.RowSource = ""
For i = 0 To rs.Fields.Count - 1
If rs.Fields(i).Type = dbText Then cboField2.AddItem rs.Fields(i).Name
Next i
End Sub
Private Sub cboField3_Enter()
Dim rs As DAO.Recordset, i As Integer
If Me.Form.FilterOn = True Then DoCmd.ShowAllRecords
Set rs = Me.RecordsetClone
cboField2.RowSourceType = "Value List"
cboField2.RowSource = ""
For i = 0 To rs.Fields.Count - 1
If rs.Fields(i).Type = dbText Then cboField2.AddItem rs.Fields(i).Name
Next i
End Sub
Private Sub Command21_Click()
Dim sfilter As String, oRS As DAO.Recordset
Dim sfilter2 As String, rs As DAO.Recordset
If IsNull(cboField) And IsNull(cboField2) And IsNull(cboField3) Then
DoCmd.ShowAllRecords
MsgBox "select a field"
Exit Sub
End If
If Not IsNull(cboField) Then
sfilter = cboField & " LIKE '" & txtBox & "*'"
DoCmd.ApplyFilter , sfilter
End If
If Not IsNull(cboField2) Then
sfilter2 = cboField2 & " LIKE '" & txtBox2 & "*'"
DoCmd.ApplyFilter , sfilter2
End If
If Not IsNull(cboField3) Then
sfilter3 = cboField3 & " LIKE '" & txtBox3 & "*'"
DoCmd.ApplyFilter , sfilter3
End If
Set oRS = Me.RecordsetClone
Set rs = Me.RecordsetClone
If oRS.RecordCount And rs.RecordCount = 0 Then
MsgBox " no record matches"
DoCmd.ShowAllRecords
End If
End Sub
Private Sub Command28_Click()
DoCmd.ShowAllRecords
End Sub

Userform variables to E-mail

I have a Userform which has 3 buttons on it and based on the click the respective text needs to be inserted in the body of the email, for this e-mail the To, CC, Subject, will be taken from Listview box in Sheet1 which inturn extracts the values stored in Sheet2 and paste it in To, CC, Subject of the email.
When i paste the code in the buttonclick () command the variables are not getting passed from the maincode to the userform code where it shows the To, CC and Subject as blanks.
Here's the code:
Sub Worksheet_Activate()
Dim rngCell As Range
ListView41.ListItems.Clear
For Each rngCell In Worksheets("MFRs Contacts").Range("A2:A400")
If Not rngCell = Empty Then
With ListView41.ListItems.Add(, , rngCell.Value)
.ListSubItems.Add , , rngCell.Offset(0, 1).Value
.ListSubItems.Add , , rngCell.Offset(0, 2).Value
End With
End If
Next rngCell
End Sub
Sub ListView41_DblClick()
Dim strName As String
Dim strEmail As String
Dim strEmail1 As String
Dim OutApp As Object
Dim OutMail As Object
Dim Singlepart As String
Dim SigString As String
Dim Signature As String
Dim strbody As String
Dim SigFilename
strName = ListView41.SelectedItem.Text
strEmail = ListView41.SelectedItem.ListSubItems(1).Text
strEmail1 = ListView41.SelectedItem.ListSubItems(2).Text
check = MsgBox("Send e-mail, To : " & strName & " - " & strEmail & "?" & vbNewLine & _
"CC : " & strEmail1, vbYesNo)
If check <> vbYes Then Exit Sub
Singlepart = MsgBox("For Single Part or Multiple Parts ? " & vbNewLine & vbNewLine & _
"Single Part = Yes" & vbNewLine & _
"Multiple Parts = No", vbYesNo)
If Singlepart = vbYes Then
' For Single Part Numbers
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<H3><B>Dear Customer Ron de Bruin</B></H3>" & _
"Please visit this website to download the new version.<br>" & _
"Let me know if you have problems.<br>" & _
"Ron's Excel Page" & _
"<br><br><B>Thank you</B>"
'Signature of User
SigString = Environ("appdata") & _
"\Microsoft\Signatures\Rohith UTAS.htm"
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
On Error Resume Next
Userform1.Show
'With Outlook
With OutMail
.Display
.To = strEmail
.CC = strEmail1
.BCC = ""
.Subject = strName & "_Request for Product Information"
.HTMLBody = strbody & vbNewLine & Signature
.Display 'or .Display if you want the user to view e-mail and send it manually
End With
Else
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Can you please help me on this.
Your variables you need to access on your form (I'm assuming strName, strEmail, and strEmail1) only have scope in Sub ListView41_DblClick(). If you need to use them in your form, you'll have to pass them as parameters (my preferred way to do it) or give them global scope.
A UserForm is a class, so you can give it properties like any other class - i.e. in UserForm1:
Private mEmail As String
Public Property Let Email(inputVal As String)
mEmail = inputVal
End Property
Public Property Get Email() As String
Email = mEmail
End Property
Then you would call it like any other object:
Dim nameless_form As UserForm1
Set nameless_form = New UserForm1
nameless_form.Email = strEmail
nameless_form.Show