Cannot run my codes for sending email in other machine - vba

I am helping my friend to develop her codes using VBA. I have successfully run these codes in my laptop yet she is encountering errors when we copy the codes to her machine.
Here's my code:
Sub Test()
Call sendingEmailWithChecklist("Book1.xlsm")
End Sub
Sub sendingEmailWithChecklist(workbookName As String)
Dim recipient As String
Dim cc As String
Dim subject As String
Dim body As Range
Dim greetings As String
Dim message As String
Dim signature As String
Dim ebody As String
Dim olApp As Outlook.Application
Dim olInsp As Outlook.Inspector
Dim wdDoc As Word.Document
Dim olEmail As Outlook.MailItem
Dim worksheetName As String
Dim content As Range
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
Sheet2.Activate
recipient = Range("B3").Value
cc = Range("B4").Value
subject = Range("B5").Value
greetings = Range("B6").Value
message = Range("B7").Value
ebody = greetings & vbNewLine & vbNewLine & message & vbNewLine
signature = Range("B8").Value
'Workbooks(workbookName).Activate
worksheetName = "Sheet1"
With olEmail
.Display
.To = recipient
.cc = cc
.subject = subject
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
Workbooks(workbookName).Worksheets(worksheetName).Activate
Workbooks(workbookName).Worksheets(worksheetName).Cells.Copy
'Range("A1:F17").Select
'Selection.Copy
End With
With olEmail
.Display
wdDoc.Range(1, 1).Paste
wdDoc.Range.InsertBefore ebody
'.Send
End With
End Sub
wdDoc.Range(1,1).Paste was her error. We have both declared same references from tools yet the error is still on this line. What could be the possible error why it doesn't run on her machine?
PS. She doesn't want to use HTMLbody.

Instead of
wdDoc.Range(1, 1).Paste
Try
wdDoc.Range.Paste

If you want to further control the way you paste your data in the body of mail you may want to use the Word Selection object (expression) instead of Range. Something like:
wdDoc.Application.Selection.PasteAndFormat wdFormatOriginalFormatting
Above paste the copied item with its original formatting. You may select other PasteAndFormat options depending on your expected outcome.

Related

email and signature formatting using Excel VBA

I have written the macros I need and Im stuck on a "simple matter". Email formatting as well as signature formatting. The signature is in plain text, but in outlook its formatted using different text color and font.
I have the following code which gives me the email in the following format:
email TITUS classification
Body of the email
Signature
Attachment
The code
Sub mail()
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Workbooks("macro.xlsm")
Set wks = wkb.Worksheets("settings")
Dim OApp As Object, OMail As Object, signature As String
Dim OStrTITUS As String
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.display
signature = OMail.body
.To = "mymail#mail.com"
.Subject = "Type your email subject here"
.Attachments.Add ActiveWorkbook.FullName
.body = "My email body" & vbNewLine & signature
.display
SendKeys "{DOWN}{DOWN}{ENTER}", True 'set classification
SendKeys "{ENTER}", True 'send to group
.Send
End With
Set OMail = Nothing
Set OApp = Nothing
End Sub
But I would like for the attachment in outlook to be in the body of the email, so the layout would be something like this
Body of the email
Attachment
Signature
You could try format as follows modified from code by #Niton
Sub mail()
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Workbooks("macro.xlsm")
Set wks = wkb.Worksheets("settings")
Dim OApp As Object, OMail As Object, signature As String
Dim OStrTITUS As String
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
signature = OMail.body
.To = "mymail#mail.com"
.Subject = "Type your email subject here"
.Display
.body = "My email body" & vbNewLine & signature
If .BodyFormat <> olFormatRichText Then .BodyFormat = olFormatRichText
.Attachments.Add wkb.FullName, 999
SendKeys "{DOWN}{DOWN}{ENTER}", True 'set classification
SendKeys "{ENTER}", True 'send to group
.Send
End With
Set OMail = Nothing
Set OApp = Nothing
End Sub

Excel VBA to Outlook: error Type Mismatch

I am trying to write a VBA code in Excel that will create an Outlook message which contains:
text in the body
a table
a signature at the bottom.
Below is a code that I wrote. It was working until I added the Excel Table object to the body of the message. It's coming up with an error message that says:
Run-time error: error type 13, Type Mismatch".
Can someone help with my code below?
Sub send()
Dim OApp As Object, OMail As Object, signature As String
Dim TOEMAIL As Range
Dim CCMEMAIL As Range
Dim SUBJECT As Range
Dim Workbook As Range
Dim Table As Range
Set TOEMAIL = Sheets("Macro").Range("D6")
Set CCEMAIL = Sheets("Macro").Range("D7")
Set SUBJECT = Sheets("Macro").Range("D8")
Set Workbook = Sheets("Macro").Range("D5")
Set Table = Sheets("Sheet1").Range("B7:B17")
Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)
With OMail
.Display
End With
signature = OMail.body
With OMail
.To = TOEMAIL
.CC = CCEMAIL
.SUBJECT = SUBJECT
.Attachments.Add (Workbook)
.body = "Hello, this is a test." & vbNewLine & Table & vbNewLine & signature & vbNewLine
End With
Set OMail = Nothing
Set OApp = Nothing
End Sub
MailItem.Body property expects a string. You are trying to concatenate a few strings and a Range object. It is your responsibility to extract the relevant data from that table and represent it as a string.
You would probably be better off creating an HTML table and setting the MailItem.HTMLBody property instead.

How to send a Word document as body of an email with VBA

I've created a macro that works with outlook and excel that will use a list of email addresses (in excel) and send all those addresses an email (in outlook). I want to take a word document (from microsoft word) and use it as the body of the email. The problem is, I will have images in the word document and I need the word document to keep it's formatting. Right now, my VBA takes the content of my word document but the formatting is gone and images aren't included. This is my code:
Sub spamEmail()
'Setting up the Excel variables.
Dim olApp As Object
Dim oMail As Outlook.MailItem
Dim iCounter As Integer
Dim Dest As Variant
Dim SDest As String
Dim Excel As Object
Dim Name As String
Dim Word As Object
Dim oAccount As Outlook.Account
Dim doc As Word.Document
Dim itm As Object
Dim MsgTxt As String
'Set the outlook account to send.
Set oAccount = Application.Session.Accounts.Item(2)
'Create excel object.
Set Excel = CreateObject("excel.application")
Excel.Visible = True
Excel.Workbooks.Open ("C:\Users\Deryl Lam\Documents\Book1.xlsx")
Excel.Workbooks("Book1.xlsx").Activate
'Create a word object.
Set Word = CreateObject("word.application")
Set doc = Word.Documents.Open _
(FileName:="C:\Users\Deryl Lam\Documents\emailBody.docx", ReadOnly:=True)
'Pulls text from file for message body
MsgTxt = doc.Range(Start:=doc.Paragraphs(1).Range.Start, _
End:=doc.Paragraphs(doc.Paragraphs.Count).Range.End)
'Loop through the excel worksheet.
For iCounter = 1 To WorksheetFunction.CountA(Workbooks("Book1.xlsx").Sheets(1).Columns(1))
'Create an email for each entry in the worksheet.
Set oMail = Application.CreateItem(olMailItem)
With oMail
SDest = Cells(iCounter, 1).Value
If SDest = "" Then
'Dont do anything if the entry is blank.
Else
'Do additional formatting on the BCC and Subject lines, add the body text from the spreadsheet, and send.
Name = Cells(iCounter, 2).Value
.BCC = SDest
.Subject = "FYI"
.Body = "Dear " & Name & "," & vbCrLf & MsgTxt
'SendUsingAccount is new in Office 2007
'Change Item(1)to the account number that you want to use
.SendUsingAccount = oAccount
.Send
End If
End With
Next iCounter
'Clean up the Outlook application.
Set olMailItm = Nothing
Set olApp = Nothing
End Sub
I've searched all over google for a solution but I haven't found one. How can I send a word document as the body of the email with it's formatting in tact and the images included?
You are getting the contents of your template document as a string, which by definition will not contain any formatting or images. You should instead copy the contents to the clipboard and then paste them into the new email.
Something like this:
Sub emailFromDoc()
Dim wd As Object, editor As Object
Dim doc As Object
Dim oMail As MailItem
Set wd = CreateObject("Word.Application")
Set doc = wd.documents.Open(...path to your doc...)
doc.Content.Copy
doc.Close
set wd = Nothing
Set oMail = Application.CreateItem(olMailItem)
With oMail
.BodyFormat = olFormatRichText
Set editor = .GetInspector.WordEditor
editor.Content.Paste
.Display
End With
End Sub
If not for the images, you could save the document as an HTML file, read its contents, then set the MailItem.HTMLBody property.
Images are more involved. I don't see a straightforward way to bring them into a message body.

Inserting email signature using vba in Excel 2013

This sub in an Excel VBA application that has worked well for years, inserting an Outlook signature into an email before displaying the email for me to send (.Display). This has worked in Excel 2007 in Windows XP and 2013 in Windows 7.
Now I have Windows 8.1 and Office 2013 this comes out with Error 91 in my error routine. Could it be a problem with one of the References? - or some change needed in the code?
Sub InsertSig2007(strSigName As String)
Dim objItem As Object
Dim objInsp As Outlook.Inspector
' requires a project reference to the
' Microsoft Office library
Dim objCBP As Office.CommandBarPopup
Dim objCBP2 As Office.CommandBarPopup
Dim objCBB As Office.CommandBarButton
Dim colCBControls As Office.CommandBarControls
Set objInsp = ActiveInspector
If Not objInsp Is Nothing Then
Set objItem = objInsp.CurrentItem
If objItem.Class = olMail Then
' get Insert menu
Set objCBP = objInsp.CommandBars.ActiveMenuBar.FindControl(, 30005)
' get Signature submenu
Set objCBP2 = objCBP.CommandBar.FindControl(, 5608)
If Not objCBP2 Is Nothing Then
Set colCBControls = objCBP2.Controls
For Each objCBB In colCBControls
Debug.Print objCBB.Caption
If objCBB.Caption = strSigName Then
objCBB.Execute ' **** see remarks
Exit For
End If
Next
End If
End If
End If
Set objInsp = Nothing
Set objItem = Nothing
Set colCBControls = Nothing
Set objCBB = Nothing
Set objCBP = Nothing
Set objCBP2 = Nothing
End Sub
"this comes out with Error 91 in my error routine" When debugging do not use an error routine. That way you see the line with the problem and can say what it is in your question.
It is probably
Set objCBP = objInsp.CommandBars.ActiveMenuBar.FindControl(, 30005)
See CommandBars.FindControl Method (Office)
"The use of CommandBars in some Microsoft Office applications has been superseded by the new ribbon component of the Microsoft Office Fluent user interface."
Note: CommandBars.ExecuteMso Method (Office) works in 2013 but I believe the signature button is not available.
You will surely find a replacement for your code here Insert Outlook Signature in mail.
Likely this one:
Sub Mail_Outlook_With_Signature_Html_2()
' Don't forget to copy the function GetBoiler in the module.
' Working in Office 2000-2013
'Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Dim SigString As String
Dim Signature As String
'Set OutApp = CreateObject("Outlook.Application")
'Set OutMail = OutApp.CreateItem(0)
Set OutMail = 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>"
'Change only Mysig.htm to the name of your signature
SigString = Environ("appdata") & _
"\Microsoft\Signatures\Mysig.htm"
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
On Error Resume Next
With OutMail
'.To = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = strbody & "<br>" & Signature
'.Send
'or use
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
'Set OutApp = Nothing
End Sub
Function GetBoiler(ByVal sFile As String) As String
'Dick Kusleika
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function

VBA retrieve HTMLBody from Outlook mail

First I create an email via Outlook:
Sub CreateHTMLMail()
'Creates a new e-mail item and modifies its properties.
Dim olApp As Outlook.Application
Dim objMail As Outlook.MailItem
Set olApp = Outlook.Application
'Create e-mail item
Set objMail = olApp.CreateItem(olMailItem)
Dim sHTML_Open As String
Dim sHTML_Introduction As String
Dim sHTML_Goodbye As String
Dim sHTML_Close As String
Dim sHTML_Process_Date As String
Dim sHTML_Processor As String
Dim sHTML_Issuer As String
Dim sHTML_Details As String
Dim sHTML_Body As String
sHTML_Open = "<HTML><BODY>"
sHTML_Introduction = "Hi team,<BR/><BR/>" & _
"Data is ready to process. Please find details as below.<BR/>"
sHTML_Process_Date = "<P ID='PROCESSDATE'>28 February 2013</P>"
sHTML_Processor = "<P ID='PROCESSOR'>AKSHAY</ID></P>"
sHTML_Issuer = "<P ID='ISSUER'>DATAGROUP.COM</ID></P>"
sHTML_Details = "<P ID='DETAILS'>" & _
"<UL>" & _
"<LI>Fimta23456 09:00:00 flor345</LI>" & _
"<LI>Fimta23456 09:00:00 flor345</LI>" & _
"</UL>" & _
"</P><BR/>"
sHTML_Goodbye = "Thanks"
sHTML_Close = "</BODY></HTML>"
sHTML_Body = sHTML_Open & sHTML_Introduction & sHTML_Process_Date & sHTML_Processor & sHTML_Issuer & _
sHTML_Details & sHTML_Goodbye & sHTML_Close
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.To = "Kim Gysen"
.Subject = "data remit file"
.HTMLBody = sHTML_Body
.Display
End With
End Sub
Via code, I want to retrieve values based on ID.
This seemed the cleanest way for me, I don't particulary like the "split" method because it's kind of hard coding; not very dynamic and kinda unreliable.
Unfortunately when I retrieve the HTML body, I cannot retrieve the original HTML, as it is distorted by Outlook:
Sub Get_OL()
Dim oFolder As MAPIFolder
Dim oItem As Variant
Dim sHTML_Body As String
Dim sHTML_Process_Date As String
Dim sHTML_Processor As String
Dim sHTML_Issuer As String
Dim sHTML_Details As String
Dim oExcel As Object
Dim oBook As Workbook
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
'Access the outlook inbox folder
Set oFolder = GetNamespace("MAPI").PickFolder
'On error resume next usually not to use, but feteching emails may give unexpected errors
On Error Resume Next
For Each oItem In oFolder.Items
If TypeOf oItem Is Outlook.MailItem Then
If oItem.Subject Like "*data remit file*" Then
'Turn off on error resume next asap
On Error GoTo 0
sHTML_Body = oItem.HTMLBody
Debug.Print sHTML_Body
Exit For
End If
End If
Next oItem
End Sub
On debug.print, this is what I get (only putting the last line of the Format):
</o:shapelayout></xml><![endif]--></head><body lang=EN-GB link=blue vlink=purple><div class=WordSection1><p class=MsoNormal>Hi team,<br><br>Data is ready to process. Please find details as below.<br><br><o:p></o:p></p><p>28 February 2013<o:p></o:p></p><p id=PROCESSOR>AKSHAY<o:p></o:p></p><p id=ISSUER>DATAGROUP.COM<o:p></o:p></p><ul type=disc><li class=MsoNormal style='mso-margin-top-alt:auto;mso-margin-bottom-alt:auto;mso-list:l0 level1 lfo1'>Fimta23456 09:00:00 flor345<o:p></o:p></li><li class=MsoNormal style='mso-margin-top-alt:auto;mso-margin-bottom-alt:auto;mso-list:l0 level1 lfo1'>Fimta23456 09:00:00 flor345<o:p></o:p></li></ul><p class=MsoNormal><br>Thanks<o:p></o:p></p></div></body></html>
I would like to retrieve the original HTML that I put in the HTMLBody.
2 ways:
1) parsing text - several things to do (not recommended: hard-coding)
All what you need is to parse text, but MSDN shows how to do it using InStr function. I would strongly suggest to use RegEx to parse html text. Note: reference to MS VBScript Regular Expressions x.x is needed.
Simple Regular Expression Tutorial for Excel VBA
2) using UserProperites of MailItem object (recommended)
If MailItem doesn't contains your propert(y)ies, than there is nothing to do ;)
How to: Add custom property