mismatch in putting a specific range into body of email - vba

I am trying to insert a range of specific cells into the body of my email
i am able to specify the range of cells i want, however, i kept getting mismatch error again.
I previously have a rather similar problem for my recipients variable too and it has been solved, thanks to David Zemens
multiple recipients email mismatch in VBA
PS: I really have not much knowledge about this email automation on outlook
I would appreciate your help. My code is below
Dim A As New Outlook.Application
Dim B As MailItem
Dim expireditems As Range
Dim addresses As String
Dim addressesrange As Range
Dim msg As String
Set expireditems = Nothing
Set A = New Outlook.Application
Set B = A.CreateItem(olMailItem)
LastR5 = ThisWorkbook.Sheets("Expired").Cells(Rows.Count, 1).End(xlUp).Row
LastR6 = ThisWorkbook.Sheets("Expired").Cells(Rows.Count, 7).End(xlUp).Row
For Each addressesrange In ThisWorkbook.Sheets("Expired").Range("G3:G" & LastR6).Cells
addresses = addresses & ";" & addressesrange.Value
Next
Set expireditems = ThisWorkbook.Sheets("Expired").Range("A2:E" & LastR5).SpecialCells(xlCellTypeVisible)
If expireditems Is Nothing Then
MsgBox "There are no expired items today"
Exit Sub
End If
msg = "Please remove the listed expired items." & vbCr & expireditems
'MISMATCH HERE AGAIN
With B
.To = addresses
.Subject = "Attention: Expired Items"
.Body = msg
.Importance = olImportanceHigh 'High importance
.Display
End With
If possible i like to know why as well.

i am able to specify the range of cells i want, however, i kept getting mismatch error again.
msg = "Please remove the listed expired items." & vbCr & expireditems
'MISMATCH HERE AGAIN
expireditems is defined as a Range. You cannot use it in a string like that.
Change the line
msg = "Please remove the listed expired items." & vbCr & expireditems
to
msg = "Please remove the listed expired items." & vbCr & expireditems.Address
Also if you want to import the range into the email body then you might also want to look at Ron's article on RangetoHTML

Related

How do I add additional text to subject using VBA in Word after referencing a table value from within the document?

I have a macro that will create an email based on a word document. The macro, once clicked, will save the word document, create an email with a predefined subject, add the recipient, create a brief message and then wait for the user to send. The subject and body will even reference the first cell in a table within the word document.
I need to be able to add text in the subject after referencing the cell from the table. But every time I add something after the referenced cell (from row 1, column 2), nothing appears. When I do something similar to the body it looks like a new line is started after referencing the cell value.
How do I stop a new line from being created so I can reference two different items in the subject? The code I pasted should have a subject of "Customers Name [cell value] #Order Number [cell value]" but it only gives "Customers Name [cell value]".
Below is a copy of the code I am using with email addresses and things removed.
Private Sub CommandButton1_Click()
Dim OL As Object
Dim EmailItem As Object
Dim Doc
Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
On Error GoTo handler
Doc.Save
On Error GoTo 0
With EmailItem
.Display
.Subject = "Customers Name " & Doc.Content.Tables(1).Cell(1, 2) & " #Order Number" & Doc.Content.Tables(1).Cell(1, 4)
.Body = "Please see the attached Notification for " & Doc.Content.Tables(1).Cell(1, 2) & " order" & _
"" & vbCrLf & _
"Let me know if you have any questions." & vbCrLf & _
"" & vbCrLf & _
"Thank you," & vbCrLf & vbCrLf & _
"INSERT SIGNATURE HERE"
'Update Recipient List here:
.To = "randomemail#email.com"
.Importance = olImportanceNormal
.Attachments.Add Doc.FullName
End With
Application.ScreenUpdating = True
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
The end of the cell marker acts like an end of a paragraph mark and that is stopping the addition of anything else into the Subject of the email.
Add the following to your code after where you Set Doc = ActiveDocument:
Dim Rng1 As Word.Range, Rng2 As Word.Range
Set Rng1 = Doc.Content.Tables(1).Cell(1, 2).Range
Rng1.MoveEnd unit:=wdCharacter, Count:=-1
Set Rng2 = Doc.Content.Tables(1).Cell(1, 4).Range
Rng2.MoveEnd unit:=wdCharacter, Count:=-1
And then replace the setting of the Subject code with this:
.Subject = "Customers Name " & Rng1.Text & " #Order Number" & Rng2.Text
There are two non-printing characters at the end of each cell. You need to remove them.
With Doc.Content.Tables(1)
Customer = Left(.Cell(1, 2).Range.Text, Len(.Cell(1, 2).Range.Text) - 2)
Order = Left(.Cell(1, 4).Range.Text, Len(.Cell(1, 4).Range.Text) - 2)
End With

Automation email in Excel

I am trying to design an excel file that will help my company with recruitment.
The task is to create a sheet for candidates that the company speaks to, we will record all the records for the candidates including their first name, last name, mobile and email address. You can see a screenshot of how everything looks here: https://imgur.com/gallery/tvAIx
As you can see there are columns for when the company speaks to the candidate and when he sends his CV to us. At the end there is also a "CV reminders" column. It has the following code =IF(ISBLANK(F2), HYPERLINK("mailto:" & D2 & "?subject=" & $O$3 & "&body=" & $P$3, "Send reminder"), "All good")
The idea is so that if CV has not been received yet, you can press the cell and it will generate a reminder email for the candidate. I want to make all the process autonomous so that it can pick out the candidate name from the relevant cell and send him a generic email like:
"Hi name from cell,
Hope you are well.
We have spoken with you on date from cell. Have you had a chance to review your CV yet? Do you have any questions?"
I am sure it is possible with VBA just don't know how. Thank you.
You should be able to handle basic VBA usage in order to achieve this.
Below is the VBA code that sends an Outlook e-mail message for Office 2000-2016. Source is http://www.rondebruin.nl
You may put the code in the SelectionChange event of the requested cell(s) and change the Body, SendTo etc. portions according to your needs. (Appearently in your case, SendTo address and some parts of Body will come from particular cells on the row of your selected cell)
Sub Mail_small_Text_Outlook()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Working in Office 2000-2016
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
On Error Resume Next
With OutMail
.To = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub

Set restrictions by ReceivedTime on mail list

Am trying to read mails that received only today. Below is the code where am restricting but its throwing an condition not valid error. The same is working fine when I gave a condition like unread = True.
Set myItems = myItems.Restrict("DateValue[ReceivedTime]='" & Format(DateValue(Now),"ddddd h:nn AMPM") & "'")
Please help me on this.
I see at least two problems.
You have "DateValue[ReceivedTime]" rather than "[ReceivedTime]".
You are restricting emails to those received at exactly midnight today rather than those received after midnight.
Try this code:
Sub RestrictByDate()
Dim FmtToday As String
Dim FldrInbox As Folder
Dim MailItemsToday As Items
Dim MailItemCrnt As MailItem
FmtToday = Format(DateValue(Now()), "ddddd h:nn AMPM")
' #### Replace "xxxx" with the name of the store containing the target Inbox
Set FldrInbox = Session.Folders("xxxx").Folders("Inbox")
Set MailItemsToday = FldrInbox.Items.Restrict("[ReceivedTime] > '" & FmtToday & "'")
Debug.Print "Number of emails received today=" & MailItemsToday.Count
For Each MailItemCrnt In MailItemsToday
With MailItemCrnt
Debug.Print .ReceivedTime & " " & .Subject
End With
Next
End Sub

Using VBA to send emails based on adjacent conditions

I'm a new VBA user and am trying to accomplish what I've described in the title using the code below.
I think it has something to do with creating dims specifically for cc/bcc/and to, but I'm not quite sure. in one column is a list of emails that have been filtered for based on specific conditions and in the column right next to it is either "" "cc" or "bcc". If it's blank, then it goes into "to" if it's cc" it goes into the .CC field etc. etc.
Sub SendList()
'DIM
Dim olApp As Outlook.Application
Dim olMail As MailItem
Dim CurrFile As String
Dim emailRng As Range, cl As Range
Dim sTo As String
'SET
Set emailRng = ActiveSheet.Range("E3:E100").SpecialCells(xlCellTypeVisible)
For Each cl In emailRng
sTo = sTo & ";" & cl.Value
Next
sTo = Mid(sTo, 2)
Set olApp = New Outlook.Application
Set olMail = olApp.CreateItem(olMailItem)
'UPDATE WORKBOOK BEFORE SENDING
ActiveWorkbook.Save
CurrFile = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
'Need to find a way to automate to TO CC and BCC
With olMail
.To = sTo
.CC = ""
.BCC = ""
.Subject = "Audit Report XYZ" & " " & "-" & " " & Date
.Body = .Body & "Test" & vbCrLf & "Test2" & vbCrLf & "Test3"
.Attachments.Add "C:\Users\uq050e\Downloads\anyfile.xlsx" 'An audit report
.Display '.Send
End With
Set olMail = Nothing
Set olApp = Nothing
End Sub
It looks like the problem is not with Outlook VBA, but with reading the Excel's content. I'd suggest learning VBA and Excel a bit first, see Getting Started with VBA in Excel 2010.
You can use the Text property of the Range class to get the text for the specified object/cell.

How to send outlook email automatically using Excel UserForm?

Thanks for any help with this. I have a userform I've made that gathers criteria from the user and then when they hit submit it opens Outlook and emails that data to me.
I'm having 2 issues. The first is that when I try to use SENDKEYS method I'm running into the spell check feature stopping the email from actually sending without the user needing to go through it. Is there a way to bypass spell check and send the email?
Secondly, I couldn't find a way to actual send an email automatically without using SENDKEYS but I'm sure there is a better way out there to send the email rather than manipulating the window with TAB key strokes.
Private Sub SubmitButton_Click()
Dim OutApp As Object
Dim OutMail As Object
Dim strBody, RequestName, ProductName, Month, TestName, Summary As String
If Me.RequesterNameTxt.Value <> "" And Me.ProductCombo.Value <> "" And Me.MonthCombo.Value <> "" And Me.TestNameCombo <> "" Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
RequestName = Me.RequesterNameTxt.Value
ProductName = Me.ProductCombo.Value
Month = Me.MonthCombo.Value
TestName = Me.TestNameCombo.Value
Summary = Me.SummaryTxt.Value
strBody = "<HTML><BODY>"
strBody = "Requester Name: " & RequestName & "<BR>" & "Product Name: " & ProductName & "<BR>" & "Month: " & Month & "<BR>" & _
"Test Name: " & TestName & "<BR>" & "<BR>" & "Summary of Request: " & Summary
strBody = strBody & "</BODY></HTML>"
On Error Resume Next
With OutMail
.To = "example#gmail.com;"
.CC = ""
.bcc = ""
.Subject = "QA Service Request"
.htmlBody = strBody
.send 'This fixed my issue. I had this as .Display which opens email up and doesn't send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
Application.SendKeys ("%s")
Else: MsgBox "Please fill out all form data before submitting request. Thank you!"
End If
End Sub
You need to use the Send method of Outlook items instead. The Send method sends an item using the default account specified for the session. In a session where multiple Microsoft Exchange accounts are defined in the profile, the first Exchange account added to the profile is the primary Exchange account, and is also the default account for the session. To specify a different account to send an item, set the SendUsingAccount property to the desired Account object and then call the Send method.
Also I'd recommend using the Recipients property for adding recipients instead. The property returns a Recipients collection that represents all the recipients for the Outlook item.