Populate an email with data from an Excel spreadsheet - excel

I have an Excel spreadsheet of contacts. I want to set a drop-down list that sends an email to the specific person I choose and returns the contact info in the body of the email.
I don't know how to get the email to auto-populate and right now, the email that pops up has "true" in the body for the contact info rather than returning the text value in the cell.
Sub DropDown7_Change()
Dim answer As String
answer = MsgBox("Are you sure you want to assign this lead?", _
vbYesNo, "Send Email")
' Above code informs the user that an automated email will be sent
'Code uses the users answer to either carryout the generated email process or to not save the changes.
If answer = vbNo Then Cancel = True
If Cancel = True Then Exit Sub
If answer = vbYes Then
'Connects to outlook and retrieves information needed to create and send the email.
Set OutlookApp = CreateObject("Outlook.Application")
Set OlObjects = OutlookApp.GetNamespace("MAPI")
Set newmsg = OutlookApp.CreateItem(olMailItem)
'Contains the email address of the person receiving the email.
newmsg.Subject = "Lead Assigned to You" 'Sets the automated subject line to the email
newmsg.Body = "Hello," & vbNewLine & _
"You have been assigned a lead. Please follow up with the contact" & vbNewLine & _
ActiveCell.Offset(0, 3).Range("K5").Select
ActiveCell.Offset(0, 6).Range("K5").Select
ActiveCell.Offset(0, 7).Range("K5").Select
'Above code has the body of the automated email
newmsg.Display
End If
End Sub ' End of function

If you are trying to get the values that are Offset to Range("K5") , then you need to use the Offset with .Value , like this Range("K5").Offset(0, 3).Value , this will get the value 3 columns to the right of Cell "K5".
The code below, will add the values from 3 cells with Columns offset to cell "K5" to you email body:
Sub DropDown7_Change()
Dim answer As String
answer = MsgBox("Are you sure you want to assign this lead?", _
vbYesNo, "Send Email")
' Above code informs the user that an automated email will be sent
'Code uses the users answer to either carryout the generated email process or to not save the changes.
If answer = vbNo Then
Exit Sub
Else
If answer = vbYes Then
'Connects to outlook and retrieves information needed to create and send the email.
Set OutlookApp = CreateObject("Outlook.Application")
Set OlObjects = OutlookApp.GetNamespace("MAPI")
Set newmsg = OutlookApp.CreateItem(olMailItem)
'Contains the email address of the person receiving the email.
newmsg.Subject = "Lead Assigned to You" 'Sets the automated subject line to the email
newmsg.body = "Hello," & vbNewLine & _
"You have been assigned a lead. Please follow up with the contact" & vbNewLine & _
Range("K5").Offset(0, 3).Value & vbNewLine & _
Range("K5").Offset(0, 6).Value & vbNewLine & _
Range("K5").Offset(0, 7).Value & vbNewLine
'Above code has the body of the automated email
newmsg.Display
End If
End If
End Sub

Related

Find two cells values in hidden sheet and store as string

My idea is to make a (Forget Password) form that will restore the (Username) & (Password) and send it via Email Address provided by the user. In the following picture the customer will enter his Email address so the procedure code will find an exact match of the Email Address in hidden sheet table, if there is a match the next two cells will be stored as a string.
As you can see down below this is the hidden sheet with a table that contains information about registered customers, so when we get Email matching the (Username) and (Password) will be stored as string ((!!without activating or seeing this sheet!!))
This is my current code:
Public Function send_email()
Dim NUser As String
Dim NPass As String
Dim info As Variant
Set cdomsg = CreateObject("CDO.message")
With cdomsg.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = "587"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "dash32762#gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "*******"
.Update
End With
' ========(( below is the code i want to find and store user and pass ))
Set info = Worksheets("AdminPanel2").Range("I11:I80").Find( _
What:=Me.txt_pass.Value, LookIn:=xlFormulas)
If Not info Is Nothing Then
info.Parent.Activate
info.Offset(0, 1).Select
NUser = ActiveCell.Text
MsgBox "That data was sent"
Else
MsgBox "That data was not found."
End If
'===========(( below code i want to recall it in body of the email ))
With cdomsg
.To = info
.From = "dash32762#gmail.com"
.Subject = "Restore information"
.TextBody = Hello youur username is NUser your password is NPass
.send
End With
Set cdomsg = Nothing
End Function
This is the code I want to modify:
' ========(( below is the code i want to find and store user and pass ))
Set info = Worksheets("AdminPanel2").Range("I11:I80").Find( _
What:=Me.txt_pass.Value, LookIn:=xlFormulas)
If Not info Is Nothing Then
info.Parent.Activate
info.Offset(0, 1).Select
NUser = ActiveCell.Text
MsgBox "That data was sent"
Else
MsgBox "That data was not found."
End If
Sending email and password in one email is very bad. Keeping email and password in a hidden Excel sheet is even worse. This is really not how it is done and if this is not some school project, you may have a lot of problems at work. The best practice is not to keep a password, but to keep its hash. And not to send the old password, but make a new one.
Having said all of the above, the .TextBody should be a string with & between the variables like this:
With cdomsg
.To = info
.From = "dash32762#gmail.com"
.Subject = "Restore information"
.TextBody = "Hello your username is" & NUser & " your password is" & NPass
.Send
End With
And concerning the part in your question:
With Worksheets("AdminPanel2").Range("I11:I80")
Set info = .Find(What:=Me.txt_pass.Value, LookIn:=xlValues, LookAt:=xlWhole)
End With
If Not info Is Nothing Then
NUser = info.Offset(0, 1)
MsgBox "That data was sent for user " & info
Else
MsgBox "That data was not found."
End If
Range.Find Method()
How to avoid using Select in Excel VBA

Sending Emails in Excel using VBA when a specific value of a cell is selected

I'm trying to send an email to recipients when a specific value of a cell is selected. If the value is 'new' then it gets sent to a predefined email. if the value is 'pending' or otherwise then it gets sent to a user entered email in another cell. I'm using this currently but i'm not sure how to modify it to look at the other cell.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim myToAdd As String
If Target.Column = 6 Then
If Target.Value = "New " Then
myToAdd = "email#hotmail.com;"
ElseIf Target.Value = "Pending review" Then
myToAdd = 'I want this to look at another cell for the email
End If
With CreateObject("Outlook.Application").createitem(0) '0 will create a new email item
.To = myToAdd
.Subject = "A change request/project support has been request"
.Body = "Dear User," & vbNewLine & vbNewLine & "This is my email body "
.Display
End With
End If
You can use Cells([row],[col]) to reference other cells in the active worksheet.
On the other hand, if the worksheet is not active you can use Sheets([sheetname]).Cells([row],[col]).
#Cullen gave a good answer, also you can use:
SomeSheet.Range(<<cellreference)
e.g.
Sheets("CoolSheet").Range("A6")

VBA: Send Email via IBM Notes, Add Signature?

I have the following vba code, which runs from Excel. It sends an email to a list of recipients in a range.
Sub Send_Email()
Dim answer As Integer
answer = MsgBox("Are you sure you want to Send All Announcements?", vbYesNo + vbQuestion, "Notice")
If answer = vbNo Then
Exit Sub
Else
Dim rnBody As Range
Dim Data As DataObject
Set rnBody = Worksheets(1).Range("N3")
rnBody.Copy
Dim Maildb As Object
Dim MailDoc As Object
Dim Body As Object
Dim Session As Object
Dim i As Long
Dim j As Long
Dim server, mailfile, user, usersig As String
Dim LastRow As Long, ws As Worksheet
LastRow = Worksheets(1).Range("F" & Rows.Count).End(xlUp).Row 'Finds the last used row
j = 18
'Start a session of Lotus Notes
Set Session = CreateObject("Lotus.NotesSession")
'This line prompts for password of current ID noted in Notes.INI
Call Session.Initialize
'Open the Mail Database of your Lotus Notes
user = Session.UserName
usersig = Session.CommonUserName
server = Session.GetEnvironmentString("MailServer", True)
mailfile = Session.GetEnvironmentString("MailFile", True)
Set Maildb = Session.GetDatabase(server, mailfile)
If Not Maildb.IsOpen = True Then Call Maildb.Open
With ThisWorkbook.Worksheets(1)
For i = 18 To LastRow
'Create the Mail Document
Session.ConvertMime = False ' Do not convert MIME to rich text
Set MailDoc = Maildb.CREATEDOCUMENT
Call MailDoc.ReplaceItemValue("Form", "Memo")
'Set From
Call MailDoc.ReplaceItemValue("Principal", "Food.Specials#Lidl.co.uk")
Call MailDoc.ReplaceItemValue("ReplyTo", "Food.Specials#Lidl.co.uk")
Call MailDoc.ReplaceItemValue("DisplaySent", "Food Specials")
Call MailDoc.ReplaceItemValue("iNetFrom", "Food.Specials#Lidl.co.uk")
Call MailDoc.ReplaceItemValue("iNetPrincipal", "Food.Specials#Lidl.co.uk")
'Set the Recipient of the mail
Call MailDoc.ReplaceItemValue("SendTo", Range("Q" & i).value)
'Call MailDoc.ReplaceItemValue("CopyTo", "food.specials#lidl.co.uk")
'Set subject of the mail
Call MailDoc.ReplaceItemValue("Subject", "Promotion Announcement for week " & Range("I8").value & ", " & Range("T8").value & " - Confirmation required")
'Create and set the Body content of the mail
Set Body = MailDoc.CREATERICHTEXTITEM("Body")
If Range("I10").value <> "" Then
Call Body.APPENDTEXT("Good " & Range("A1").value & "," & vbNewLine & vbNewLine _
& "Please see attached an announcement of the spot buy promotion for week " & Range("I8").value & ", " & Range("T8").value & "." & vbNewLine & vbNewLine _
& "Please can you confirm within 24 hours." & vbNewLine & vbNewLine _
& Range("I10").value & vbNewLine)
Else
Call Body.APPENDTEXT("Good " & Range("A1").value & "," & vbNewLine & vbNewLine _
& "Please see attached an announcement of the spot buy promotion for week " & Range("I8").value & ", " & Range("T8").value & "." & vbNewLine & vbNewLine _
& "Please can you confirm within 24 hours." & vbNewLine)
End If
'Embed Excel Sheet Range
Set Data = New DataObject
Data.GetFromClipboard
Call Body.ADDNEWLINE(2)
Call Body.EmbedObject(1454, "", Range("F" & i).value, "Attachment")
'create an attachment (optional)
Call Body.ADDNEWLINE(3)
Call Body.APPENDTEXT(Data.GetText)
'create an attachment (optional)
Call Body.ADDNEWLINE(4)
Call Body.APPENDTEXT(Maildb.GetProfileDocument("CalendarProfile").GetItemValue("Signature")(0))
'Example to save the message (optional) in Sent items
MailDoc.SaveMessageOnSend = True
'Send the document
'Gets the mail to appear in the Sent items folder
Call MailDoc.ReplaceItemValue("PostedDate", Now())
Call MailDoc.Send(False)
Set MailDoc = Nothing
j = j + 1
Next i
End With
'Clean Up the Object variables - Recover memory
Set Maildb = Nothing
Set Body = Nothing
Set Session = Nothing
Application.CutCopyMode = False
MsgBox "Success!" & vbNewLine & "Announcements have been sent."
End If
End Sub
The code semi works. Emails are sent fine.
However, i want to be able to add the default signature to the bottom of my email. I am trying to do this using this line but its not adding any signature.
'create an attachment (optional)
Call Body.ADDNEWLINE(4)
Call Body.APPENDTEXT(Maildb.GetProfileDocument("CalendarProfile").GetItemValue("Signature")(0))
My signature contains an image, and i'm wondering if this won't pull through the signature because my email isn't html?
In which case then, how could i change this email to html?
Please can someone show me what i am doing wrong?
Your suspicion is correct. This won't work since you're creating a Notes rich text email message - but the solution is not necessarily switching to creating a MIME/HTML message. The NotesRichTextItem class's AppendText method can only handle text, but if the Notes signature is in rich text format, it's actually the Signature_Rich item that you should be working with, not the Signature item, and you should be using the AppendRTItem method instead of the AppendText method.
The truth is, though, that with two different mail formats and several different options for the way the signature is managed in the user's profile, this is a non-trivial problem to handle for all of the different cases that you might have to handle. You really have to look at the SignatureOption item value, which is "3" if it is rich text, "2" if it's an HTML or image file, and "1" if it is plain text. The solution in your code is going to be different depending on which one is being used, and coping with option 2 while creating a rich text message isn't going to be easy.
You might want to check out the answer to this previous question for an example of building a MIME message if you want to get away from using Notes rich text. And while I haven't vetted the code in this blog post, it shows appending a signature - it looks like it is assuming that the signature is in a file rather than checking the SignatureOptions item.

Automate trigger from email that has been replied

I am new in VBA. I would like to ask on how to trigger email which has been reply.
Scenario : I have this coding as below which send the email to recipient (Column B) if there is "yes" in column C.
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*#?*.?*" And _
LCase(Cells(cell.Row, "C").Value) = "yes" Then
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = cell.Value
.Subject = "Reminder"
.Body = "Dear " & Cells(cell.Row, "A").Value _
& vbNewLine & vbNewLine & _
"Please contact us to discuss bringing " & _
"your account up to date"
'You can add files also like this
'.Attachments.Add ("C:\test.txt")
.Send 'Or use Display
End With
Question : How can I trigger if the recipient has replied to my email that I sent earlier? I would like to automate the trigger to my excel file on column E as remark recipient has replied to my email. Ex, "replied / no reply".
Really appreciate for any help since I am new in VBA.
Thank you.
Assuming your using Microsoft Outlook and an Exchange Server.
There are 3 Extended MAPI properties that deal with the message state for replied to/forwarded:
PR_ICON_INDEX (0x10800003)
PR_LAST_VERB_EXECUTED (0x10810003)
PR_LAST_VERB_EXECUTION_TIME (0x10820040)
This MSDN article https://msdn.microsoft.com/en-us/library/bb176395(office.12).aspx provides code that shows how to use these MAPI Properties:
Sub DemoPropertyAccessorGetProperty()
Dim PropName, Header As String
Dim oMail As Object
Dim oPA As Outlook.PropertyAccessor
'Get first item in the inbox
Set oMail = _
Application.Session.GetDefaultFolder(olFolderInbox).Items(1)
'PR_TRANSPORT_MESSAGE_HEADERS
PropName = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
'Obtain an instance of PropertyAccessor class
Set oPA = oMail.PropertyAccessor
'Call GetProperty
Header = oPA.GetProperty(PropName)
Debug.Print (Header)
End Sub
You will want to replace the 'PR_TRANSPORT_MESSAGE_HEADERS ie 0x007D001E in the above code and I'm guessing you'll want to go through more than just the first mail item...

Excel VBA code to read a username from a cell then send an email to that user

I require some help in creating Excel VBA code which will read a row of usernames from cells in Excel and then send an email to all those users by searching for the users email address in the Outlook contacts list.
I have managed to write the code that will bring up outlook's compose email dialog box from the spreadsheet.
You can use for in range with mails and call this proc to send email
Public Sub SendMail(MailTO As String, MailSubject As String, MailBody As String)
'http://officevb.com
Dim appOL As Object
Dim myEmail As Object
Dim TxtHello As String
Set appOL = CreateObject("Outlook.Application")
Set myEmail = appOL.CreateItem(olMailItem)
'Use hour to create a text
Select Case Hour(Time)
Case Is <= 12
TxtHello = "Good Morning," & vbNewLine
Case Is >= 12
TxtHello = "Good Afternoom," & vbNewLine
Case Is >= 18
TxtHello = "Good Night," & vbNewLine
End Select
With myEmail
.display
.Recipients.Add MailTO
.Subject = MailSubject
.Body = TxtHello & MailBody
.Send
End With
Set myEmail = Nothing
Set appOL = Nothing
End Sub
call this sub passing these parameters
sendMail "Mail#yourContact.com","Test","This is a automatic mail"
[]´s

Resources