Make Outlook Task item through Excel Button - excel

I want to make a simple program in which I can create an Outlook Task. User fills in data and clicks the create button.
I found the following code online and it should work, but it doesn't. No task is added in my Outlook, but no error is shown either. I have the feeling it somehow goes wrong with adding the recipients of the task.
Any clue why I don't get an error but, no tasks are added?
Dim OutApp As Outlook.Application
Dim OutTask As Outlook.TaskItem
Set OutApp = CreateObject("Outlook.Application")
Set OutTask = OutApp.CreateItem(olTaskItem)
Set myRecipient = OutTask.Recipients.Add("I.wont.write.my.actual.address.in.this#example.com")
myRecipient.Type = olTo
If myRecipient.Resolved Then
With OutTask
.Display
.Subject = Cells(3, "I")
.StartDate = Now
.DueDate = Cells(2, "I")
.Body = "Please see the attached email for a service request assigned to you."
End With
End If
Set OutTask = Nothing
Set OutApp = Nothing
I just can't figure it out and it's really breaking my brain at the moment. Hope someone can hint me in the right direction!

I found the following code online and it should work, but it doesn't. No task is added in my Outlook, but no error is shown either. I have the feeling it somehow goes wrong with adding the recipients of the task.
Correct - Attempt to resolve the Recipient object myRecipient.Resolve against the Address Book before assuming its resolved If myRecipient.Resolved Then also defined variable Dim myRecipient As Outlook.Recipient for myRecipient
Option Explicit
Sub tasks()
Dim OutApp As Outlook.Application
Set OutApp = CreateObject("Outlook.Application")
Dim OutTask As Outlook.TaskItem
Set OutTask = OutApp.CreateItem(olTaskItem)
Dim myRecipient As Outlook.Recipient
Set myRecipient = OutTask.Recipients.Add("0m3r#Email.com")
myRecipient.Type = olTo
myRecipient.Resolve
If myRecipient.Resolved Then
With OutTask
.Display
.Subject = Cells(3, "I")
.StartDate = Now
.DueDate = Cells(2, "I")
.Body = "Please see the attached email."
End With
End If
Set OutTask = Nothing
Set OutApp = Nothing
End Sub
Option Explicit Statement (Visual Basic)
Forces explicit declaration of all variables in a file, or allows implicit declarations of variables.

Check this examples, run each one and see if they are usefull to you, hope one fit your needs:
Sub outlook_send_followup()
' High importance = 2
' Nothing = 1
' Low importance = 0
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
Dim MyItem As Object
Set MyItem = OutApp.CreateItem(olMailItem)
With MyItem
.To = "example#hotmail.com"
.Subject = "hi, this is a task"
.SentOnBehalfOfName = "example#hotmail.com"
.HTMLBody = "<HTML MSG FORMAT HERE>"
.Importance = 1
.FlagStatus = olFlagMarked
.FlagRequest = "Follow up"
.FlagDueBy = Now
.Display
End With
Set MyItem = Nothing
Set OutApp = Nothing
End Sub
Sub create_outlook_taks()
'Const olImportanceLow = 0
'Const olImportanceNormal = 1
'Const olImportanceHigh = 2
Dim outlook_app As Object
Set outlook_app = CreateObject("Outlook.Application")
With outlook_app.CreateItem(3)
.Importance = 2
.Subject = "THIS IS A TASK"
.StartDate = Now + 5
.DueDate = Now + 10
.ReminderTime = Now - 3
.Body = "HI YOU CREATED THIS TASK"
.Display
'.Save
End With
Set outlook_app = Nothing
End Sub

Related

Excel macro to send an email generates runtime error 287

I referenced many websites and even copied and pasted code. I cannot get my Excel macro button to send an email.
When I click RunSub/Userform(play button) in VBAProject I get
runtime error 287
Sub Send_Email()
Dim MyOutlook As Object
Set MyOutlook = CreateObject("Outlook.Application")
Dim MyMail As Object
Set MyMail = MyOutlook.CreateItem(olMailItem)
MyMail.To = "notlistedpublicly"
MyMail.Subject = Range("B6") & "Has completed his Skills Matrix"
MyMail.Body = Range("B6") & "has completed his Skills Matrix. Please review"
MyMail.Send
End Sub
I have a similar code, I added some lines to from it to your code.
Sub Send_Email()
Dim MyOutlook As Object
Set MyOutlook = CreateObject("Outlook.Application")
Dim MyMail As Object
'I change this
'Set MyMail = MyOutlook.CreateItem(olMailItem)
Set MyMail = MyOutlook.CreateItem(0)
MyOutlook.Session.Logon
With MyMail
.To = "notlistedpublicly"
.Subject = Range("B6") & "Has completed his Skills Matrix"
.Body = Range("B6") & "has completed his Skills Matrix. Please review"
'Before try to see how the mail looks.
'.Send
.Display
End with
Set MyMail = Nothing
Set MyOutlook = Nothing
End Sub

Checking a string value to return a range from another worksheet then add to .To line in email

I am trying to get email addresses from a worksheet(Sheet1) into the .To line for an outlook email based on the specific string value in the main worksheet.
I have managed to play with it several ways but none have given the results I need. The idea is that it checks a cell on the main worksheet for a specific string value, then would reference a specific range of cells in one column from another worksheet based on the string value and include these emails in the .To line, separated by a";".
I also noticed it removed data from the cells when it pulled it in testing, replacing some cells with "Column1"
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim emailRng As Range, cl As Range
Dim sTo As String
Set emailRng = Worksheets("SHEET1").Range("D3:D20")
For Each cl In emailRng
sTo = sTo & ";" & cl.Value
Next
sTo = Mid(sTo, 2)
If InStr(ActiveCell.Value, "ABC") > 0 Then
emailRng = ThisWorkbook.Sheets("SHEET1").Range("D3:D5")
ElseIf InStr(ActiveCell.Value, "XYZ") > 0 Then
emailRng = ThisWorkbook.Sheets("SHEET1").Range("D11:D15")
End If
If Target.CountLarge > 1 Then Exit Sub
Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")
Select Case Target.Column
Case Is = 15
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = sTo
.CC = "REQ#EMAIL.COM"
.Subject = ""
.HTMLBody = "Please attend "
.Display
End With
End Select
Application.ScreenUpdating = False
End Sub
First of all, creating a new Outlook Application instance in the Worksheet_BeforeDoubleClick handler is not really a good idea. Consider creating an Outlook instance once and then only create a new email in the event handler instead.
Instead of relying on To or CC properties:
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = sTo
.CC = "REQ#EMAIL.COM"
.Subject = ""
.HTMLBody = "Please attend "
.Display
End With
I'd recommend using the Recipients property of the MailItem class which returns a Recipients collection that represents all the recipients for the Outlook item. For example:
Sub CreateStatusReportToBoss()
Dim myItem As Outlook.MailItem
Dim myRecipient As Outlook.Recipient
Set myItem = Application.CreateItem(olMailItem)
Set myRecipient = myItem.Recipients.Add("Eugene Astafiev")
myItem.Subject = "Status Report"
myItem.Display
End Sub
Then I'd recommend using the Resolve or ResolveAll method which attempts to resolve all the Recipient objects in the Recipients collection against the Address Book.
Sub CheckRecipients()
Dim MyItem As Outlook.MailItem
Dim myRecipients As Outlook.Recipients
Dim myRecipient As Outlook.Recipient
Set myItem = Application.CreateItem(olMailItem)
Set myRecipients = myItem.Recipients
myRecipients.Add("Eugene Astafiev")
myRecipients.Add("Dmitry Anafriev")
myRecipients.Add("Tom Wilon")
If Not myRecipients.ResolveAll Then
For Each myRecipient In myRecipients
If Not myRecipient.Resolved Then
MsgBox myRecipient.Name
End If
Next
End If
End Sub
You may find the How To: Fill TO,CC and BCC fields in Outlook programmatically article helpful.

How do I reply to outlook mail using vba in excel with mail thread?

I am looking for VBA code in excel to reply to a selected mail but the below code creates seperate mail which does not have previous messages in conversation (thread) in body. I searched online, but most of them are old codes which are not working currently. Please help.
Sub Test_template()
Dim emailApplication As Object
Dim emailItem As Object
Set emailApplication = CreateObject("Outlook.Application")
Set emailItem = emailApplication.ActiveExplorer.Selection.Item(1).ReplyAll
emailItem.bcc = "XYZ.com"
emailItem.Body = "Hi, have a nice day "
emailItem.Display
Set emailItem = Nothing
Set emailApplication = Nothing
End Sub
Is this what you are trying? I have commented the code and provided relevant MSDN links. If you still get stuck then simply ask.
Option Explicit
Sub Sample()
Dim OutlookApp As Object
Dim OutlookMail As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.ActiveExplorer.Selection.Item(1)
'~~> Get MailItem.GetConversation method (Outlook)
' https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.getconversation
Dim OutlookConversation As Object
Set OutlookConversation = OutlookMail.GetConversation
'~~> Conversation.GetTable method (Outlook)
' https://learn.microsoft.com/en-us/office/vba/api/outlook.conversation.gettable
Dim OutlookTable As Object
Set OutlookTable = OutlookConversation.GetTable
'~~> Obtains a 2D array from the Table.
' https://learn.microsoft.com/en-us/office/vba/api/outlook.table.getarray
Dim OutlookAr As Variant
OutlookAr = OutlookTable.GetArray(OutlookTable.GetRowCount)
Dim OutlookReplyToThisMail As Object
Set OutlookReplyToThisMail = OutlookMail.Session.GetItemFromID(OutlookAr(UBound(OutlookAr), 0))
Dim MyMessage As String: MyMessage = "Hi, have a nice day "
With OutlookReplyToThisMail.ReplyAll
.BCC = "XYZ.com"
.HTMLBody = MyMessage & .HTMLBody
.Display
End With
End Sub
.ReplyAll produces the expected result but is overwritten by emailItem.Body = "Hi, have a nice day ".
Option Explicit
Sub Test_template()
Dim emailApplication As Object
Dim emailItem As Object
'Set emailApplication = CreateObject("Outlook.Application")
' mail has to be slelected in Outlook application so it has to be open already
Set emailApplication = GetObject(, "Outlook.Application")
Set emailItem = emailApplication.ActiveExplorer.Selection.Item(1).ReplyAll
emailItem.BCC = "XYZ.com"
'emailItem.Body = "Hi, have a nice day "
emailItem.Body = "Hi, have a nice day " & emailItem.Body
' or
'emailItem.htmlBody = "Hi, have a nice day " & emailItem.htmlBody
emailItem.Display
Set emailItem = Nothing
Set emailApplication = Nothing
End Sub

How to send email from a specific Outlook account using Excel?

I have code that sends emails using the default Outlook account.
I tried changing the code to send from a specific email. When I run the macro, nothing happens.
Is something wrong with the code, or is it not working due to another issue (with Outlook and the accounts/permissions associated with it)?
Sub CommandButton1_Click()
Dim wb As Workbook
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Dim q As Long
Dim oAccount As Outlook.Account
Set wb = ThisWorkbook
For Each oAccount In Outlook.Application.Session.Accounts
If oAccount = "theEmailiWantToUse#domain.com" Then
For q = 2 To 3 'LastRow
eName = wb.Sheets(1).Cells(q, 2).Value
Set olApp = New Outlook.Application
Set olMail = olApp.CreateItem(olMailItem)
mailBody = "Hello, "
With olMail
.To = Worksheets("Emails").Cells(q, 4).Value
.Subject = eName
.HTMLBody = "<!DOCTYPE html><html><head><style>"
.HTMLBody = .HTMLBody & "body{font-family: Calibri, ""Times New Roman"", sans-serif; font-size: 14px}"
.HTMLBody = .HTMLBody & "</style></head><body>"
.HTMLBody = .HTMLBody & mailBody & "</body></html>"
Set .SendUsingAccount = oAccount
.Display
' .Send
End With
Next
Else
End If
Next
Set olMail = Nothing
Set olApp = Nothing
End Sub
I know I have access to the email I would like to send emails from, as I can select it from Outlook and it works.
Add this line within the olMail
.SentOnBehalfOfName = "youraddress" 'here change this
please use this routine to find Account number of sender .
Sub Which_Account_Number()
'Don't forget to set a reference to Outlook in the VBA editor
Dim OutApp As Outlook.Application
Dim I As Long
Set OutApp = CreateObject("Outlook.Application")
For I = 1 To OutApp.Session.Accounts.Count
MsgBox OutApp.Session.Accounts.Item(I) & " : This is account number " & I
Next I
End Sub
Then
.SendUsingAccount = olApp.Session.Accounts.Item(5)' whatever account index number you want to send. i have chosen 5
instead of
Set .SendUsingAccount = oAccount
This method works for me . You can further integrate this concept in your programme. Please ensure Reference to Outlook Object Library is set in Tools/References.

VBA .Attachments.Add method throwing error

I'm trying to send and email with an attachment with VBA. The code works fine without the Attachments.Add line, but with it it get the error "Run-time error '440': The operation failed."
I've looked online and can't seem to find a reason for this. Am I not setting the email object correctly?
Code below:
Sub test()
Static objOutlook
Dim objMailItem
Dim objFileSystem
Dim objNamespace
Dim objSentFolder
Const olFolderInbox As Long = 6
Set objOutlook = CreateObject("Outlook.Application")
objOutlook.Session.GetDefaultFolder(olFolderInbox).Display
objOutlook.ActiveExplorer.WindowState = WindowState
Set objMailItem = objOutlook.CreateItem(0)
objMailItem.Display
With objMailItem
.Subject = "test"
Set recip = .Recipients.Add("cats#cats.com")
.Attachments.Add = "file.xls"
.Body = ""
.DeleteAfterSubmit = False
End With
objMailItem.Send
Set objFileSystem = Nothing
Set objMailItem = Nothing
Set objOutlook = Nothing
End Sub
.Attachments.Add "file.xls"
there is no = required (or allowed...)
If you're not doing so already, you should pass the full path to the file, and not just the name, otherwise your code may fail if the current directory is not what you expect.

Resources