Creating and assigning tasks in Outlook from Excel - vba

I am attempting to create a service desk tool in Excel, and the way I am thinking of making it easy for the admin to assign them would be to use the tasks in Outlook.
The admin person would receive the email, fill out a line in Excel, then click on a button to open a new task in Outlook, with fields pre-filled out. Then they would drag and drop the email as an attachment.
However, I am trying to get the assigned to email address pre-filled from a value in the spreadsheet. Assign doesn't seem to work, and neither does Recipient. Does anyone have any ideas why not? This is the code that I have so far:
Dim OutApp As Outlook.Application
Dim OutTask As Outlook.TaskItem
Set OutApp = CreateObject("Outlook.Application")
Set OutTask = OutApp.CreateItem(olTaskItem)
With OutTask
.Assign = Cells(2, "G")
.Subject = "Service Request" & Cells(2, "A")
.StartDate = Cells(2, "H")
.DueDate = Cells(2, "H") + Cells(2, "I")
.ReminderTime = .DueDate - 1
.Body = "Please see the attached email for a service request assigned to you."
.Display
End With
Set OutTsk = Nothing
Set OutApp = Nothing
End Sub
Any help would be greatly appreciated!

Have a look at the sample here https://msdn.microsoft.com/en-us/library/office/ff869880(v=office.15).aspx
provided by microsoft
Assign is a method and you are using it like a property.
Receipients are a collection, so you have to add them, again you cant assign them like a property
Also you have misspelt OutTsk at the end. What I would do as a matter of course when programming is turn on Option Explicit this stops misspelt variables from ruining your day.
So try something like this
Sub tasks()
Dim OutApp As Outlook.Application
Dim OutTask As Outlook.TaskItem
Set OutApp = CreateObject("Outlook.Application")
Set OutTask = OutApp.CreateItem(olTaskItem)
Dim myRecipient As Outlook.Recipient
Set myRecipient = OutTask.Recipients.Add(Cells(2, "C"))
myRecipient.Resolve
If myRecipient.Resolved Then
With OutTask
.Subject = "Service Request" & Cells(2, "A")
.StartDate = Cells(2, "H")
.DueDate = Cells(2, "H") + Cells(2, "I")
.ReminderTime = .DueDate - 1
.Body = "Please see the attached email for a service request assigned to you."
.Assign
.Display
End With
End If
Set OutTask = Nothing
Set OutApp = Nothing
End Sub

Related

Body missing from first email in list sent using VBA

I'm working on a way to send emails to a list of recipients. All emails should contain the same body, but with unique attachments. The code I'm using successfully retrieves the addresses from column N, and inserts attachments based on paths in corresponding rows in columns O:AZ.
The issue I'm encountering is that the first email created using the code has no body. The recipient and attachments are correct, but the email itself is empty. All other emails created show the body correctly. I have very little experience with VBA, and cannot find what's causing the issue.
Any help regarding the code and possible issues would be appreciated! Please let me know if you need more details regarding the code or data.
Sub create_emails()
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
Dim strobody As String
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet2")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("N").Cells.SpecialCells(xlCellTypeConstants) 'email addresses located in Sheet2, column N
Set rng = sh.Cells(cell.Row, 1).Range("O1:AZ1") 'File paths stored in corresponding rows, columns 0:AZ
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.SentOnBehalfOfName = "xxx#xxx.xxx"
.To = cell.Value
.Subject = "test subject"
.Body = strbody
strbody = "Test text"
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Display 'Or use .Display / .Send
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
You're setting strbody after you're using it, so the first time it's used it's empty.
Change:
With OutMail
.SentOnBehalfOfName = "xxx#xxx.xxx"
.To = cell.Value
.Subject = "test subject"
.Body = strbody
strbody = "Test text"
To:
With OutMail
.SentOnBehalfOfName = "xxx#xxx.xxx"
.To = cell.Value
.Subject = "test subject"
strbody = "Test text"
.Body = strbody
And also, if you had Option Explicit set, you'd notice that your declaration for strbody is mistyped to strobody.

Send Automatic Email for loop

I have a code:
Sub sendEmail()
Dim OutlookApp As Object
Dim OutlookItem As Object
Dim i As Integer
Dim Address As String
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookItem = OutlookApp.CreateItem(0)
With OutlookItem
For i = 4 To 15
If Cells(i, 18) <= Cells(i, 6) Then
Address = Cells(i, 14).Value
Set OutlookApp = CreateObject("Outlook.application")
Set OutlookItem = OutlookApp.CreateItem(0)
.To = Address
.Subject = "Calibration Due Soon !!!"
.Body = "Reminder: Calibration of " & Cells(i, 4) & "is due on " & Cells(i, 9)
.Send
Set OutlookItem = Nothing
Set OutlookApp = Nothing
'Application.Wait (Now + #12:00:08 AM#)
ElseIf Cells(i, 18) > Cells(i, 15) Then
Exit Sub
ElseIf Cells(i, 18) = "" And Cells(i, 15) = "" Then
Exit Sub
End If
Next i
End With
End Sub
It does send only first email then it prompts me with run-time error saying :
The item has been moved or deleted
And debugger highlights the " .To = Address" line.
When I use .Display instead of send it works.
Any ideas?
Re-creating the Outlook application object in every loop iteration does not make sense. It's equivalent to killing Outlook and re-starting it for every mail you send. Let's not do that.
First, set a reference to the "Microsoft Outlook 15.0 Object Library" in your Excel VBA project (or whatever version you happen to have installed).
Now you can create an Outlook object directly with New and it also enables the autocompletion and all the Outlook-specific constants, like olMailItem.
Now your code can be condensed to something like this:
Sub sendEmail()
Dim OutlookApp As New Outlook.Application
Dim r As Range
For Each r In ActiveSheet.Range("4:15").Rows
If r.Cells(18) <= r.Cells(6) And r.Cells(18) > "" And r.Cells(15) > "" Then
With OutlookApp.CreateItem(olMailItem)
.To = r.Cells(14)
.Subject = "Calibration Due Soon !!!"
.Body = "Reminder: Calibration of " & r.Cells(4) & " is due on " & r.Cells(9)
.Send
End With
End If
Next r
OutlookApp.Quit
Set OutlookApp = Nothing
End Sub

Sending multiple and and different attachments through VBA and Outlook

I'm by no means an expert and I want to send the multiple and different attachments (e.g. Person1 receives BOTH attch.1 and attach.2; Person2 receives attch.3 and attch. 5 etc).
My code:
Sub SendEmail(what_address As String, subject_line As String, mail_body As String)
Dim dlApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)
olMail.To = what_address
olMail.Subject = subject_line
olMail.Body = mail_body
olMail.Send
End Sub
Sub SendMassEmail()
Dim mail_body_message As String
Dim title As String
row_number = 1
Do
DoEvents
row_number = row_number + 1
mail_body_message = Sheet1.Range("D2")
title = Sheet1.Range("B" & row_number)
mail_body_message = Replace(mail_body_message, "replace_name_here", title)
Call SendEmail(Sheet1.Range("A" & row_number), "This is a test", mail_body_message)
Loop Until row_number = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
End Sub
I think your code requires some work but the snippet below should help with adding multiple attachments. I have tried to add annotations that might be helpful.
Please note that the full path for each attachment must be known.
For example:
C:\TestFolder\TestSubfolder\TestFile.txt
You should be able to use the same looping concept to traverse across columns to handle multiple emails. It would be difficult to suggest the exact looping to be used without knowing the structure of your spreadsheet.
Sub GenerateEmails()
Dim OutApp As Object
Dim OutMail As Object
Dim myRange As Range
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = Outlook.Application.CreateItem(olMailItem)
'This will only generate a single email with multiple attachments.
'You will need another loop or something similar to process multiple emails the loop could
'be similar to the loop below that use offset to go down rows but instead
'you will offest across columns
With OutMail
'I have used hard coded cell ranges to define the values but you can use other
'methods.
.Subject = Range("A1").Value
.To = Range("A2").Value
.CC = Range("A3").Value
.Body = Range("A4").Value
'This is where you list of attachments will start
Set myRange = Range("A5")
'Keep going down one cell until no more attachment values are provided
Do Until myRange.Value = ""
'The value here needs to be the full attachment path including file name and extension
.Attachments.Add (myRange.Value)
'Set the range to be the next cell down
Set myRange = myRange.Offset(1, 0)
Loop
'This displays the email without sending.
.Display
'Once the code is correct you can use the .Send instead to actually send the emails.
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub

Email Multiple Recipients VBA Error

Looking for help with sending emails to a list of people. My code has a simple loop and grabs the value each time through of where to send the email. While testing, the first email will always get sent. After that, the 2nd time through I get error on ".To"
Run-time error - '-2147221238 (8004010a):
The item has been moved or deleted.
This is puzzling to me because the code does accurately grab the next email value?
The emails need to be sent one by one, instead of adding the recipients to a list of bcc. Is this possible with VBA? Thanks in advance!
Sub TestingAgain()
'Setting up the Excel variables.
Dim outApp As Object
Dim outMailItem As Object
Dim iCounter As Integer
Dim sDest As String
Dim sName As String
'Create the Outlook application and the empty email.
Set outApp = CreateObject("Outlook.Application")
Set outMailItem = outApp.CreateItem(0)
With outMailItem
sDest = ""
For i = 2 To WorksheetFunction.CountA(Columns(1))
If i <> "" Then
'Grab first name and email
sDest = Cells(i, 5).Value
sName = Cells(i, 1).Value
'Send each email
.To = sDest
.Subject = "FYI"
.htmlbody = "Some stuff"
.Send
Else
MsgBox ("Error")
End If
Next i
End With
'Clean up the Outlook application.
Set outMailItem = Nothing
Set outApp = Nothing
End Sub
When you send the e-mail, the mailItem instance is done and not available anymore. Refactor your code like :
Sub TestingAgain()
'Setting up the Excel variables.
Dim outApp As Object
Dim outMailItem As Object
Dim iCounter As Integer
Dim sDest As String
Dim sName As String
'Create the Outlook application and the empty email.
Set outApp = CreateObject("Outlook.Application")
sDest = ""
For i = 2 To WorksheetFunction.CountA(Columns(1))
If i <> "" Then
'/ Create the mail item instance.
Set outMailItem = outApp.CreateItem(0)
With outMailItem
'Grab first name and email
sDest = Cells(i, 5).Value
sName = Cells(i, 1).Value
'Send each email
.To = sDest
.Subject = "FYI"
.htmlbody = "Some stuff"
.send
'/ Once sent, mail item is no more available.
End With
Else
MsgBox ("Error")
End If
Next
'Clean up the Outlook application.
Set outMailItem = Nothing
Set outApp = Nothing
End Sub

Can't figure out Object required error

The purpose of the code is to send an email to a list of addresses. To determine the start point, a user form will appear asking for the stating Column and Row (with plans that as I improve, I'll add other options in).
I had the code working, however, I made some tweaks and not keep getting an Object required error which I've tried figuring out for hours without luck. Please can you take a look at my code and suggest where I might be going wrong?
NB. I also tried declaring all variables but it didn't fix the issue.
The error is on the Loop Until username.Value = ""
Sub cmdGo_Click()
Application.DisplayAlerts = False
i = cmbRow
If i = "" Then
Exit Sub
End If
username = cmbColumn
If username = "" Then
Exit Sub
End If
Select Case username
Case "A", "a"
username = Cells(i, "a").Value
Case "B", "b"
username = Cells(i, "b").Value
Case "C", "c"
username = Cells(i, "c").Value
Case "D", "d"
username = Cells(i, "d").Value
Case "E", "e"
username = Cells(i, "e").Value
End Select
Do
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = username
.CC = ""
.BCC = ""
.Importance = 1
.Subject = "Hello"
.HTMLBody = "Message"
'display shows each email before sending
.Display
'send sends email automatically
' .Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
Application.DisplayAlerts = True
i = i + 1
Loop Until username.Value = ""
End Sub
There are few syntax and understanding mistakes in the code. I have listed them below and refactored your code a bit to help to get it work as you desire.
It's always best to use Option Explicit at the top of each module and explicitly declare variables with the desired type
Place the setting of the username inside the loop so it resets each time with a new email based on the i = i+1 counter.
Rest of comments are in code:
Option Explicit
Sub cmdGo_Click()
Application.DisplayAlerts = False
If cmbRow = "" or cmbColumn = "" Then
Exit Sub
End If
Dim i As Long
i = cmbRow
Dim UserNameCol As String 'created a new variable just to get column letter so can be used later in the loop and removed the `Select Case` block.
UserNameCol = cmbColumn
'set outlook outside loop since you only need to call it once, doing it in loop creates unneccesary processing
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Do Until Len(Cells(i, UserNameCol).Value) = 0 'will stop when blank cell appears
Dim UserName As String
UserName = Cells(i, UserNameCol).Value 'always will user whatever column choosen
Set OutMail = OutApp.CreateItem(0) 'this goes here because a new email is needed each time
On Error Resume Next
With OutMail
.To = UserName
'.CC = "" 'you can remove this lines because you are not putting anything in the field
'.BCC = "" 'you can remove this lines because you are not putting anything in the field
.Importance = 1
.Subject = "Hello"
.HTMLBody = "Message"
'display shows each email before sending
.Display
'send sends email automatically
'.Send
End With
On Error GoTo 0
i = i + 1
Loop
'destroy outlook when finished processing all mails
Set OutMail = Nothing
Set OutApp = Nothing
Application.DisplayAlerts = True
End Sub