Looping over recipients in a Outlook Appointments - excel

I using this code and trying to access the Recipients (Email Address and also Display Name) of each Outlook Appointment but getting a Error:
Run-time error '287' Application-defined or object-defined error
This error is highlighted on the line : For Each recip In olApt.recipients
Sub ListAppointments()
Dim olApp As Object
Dim olNS As Object
Dim olFolder As Object
Dim olApt As Object
Dim NextRow As Long
Dim FromDate As Date
Dim ToDate As Date
FromDate = CDate("01/04/2019")
ToDate = CDate("14/04/2019")
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9) 'olFolderCalendar
NextRow = 2
With Sheets("Sheet1") 'Change the name of the sheet here
.Range("A1:D1").Value = Array("Meeting", "Date", "Location", "Invitees")
For Each olApt In olFolder.Items
If (olApt.Start >= FromDate And olApt.Start <= ToDate) Then
.Cells(NextRow, "A").Value = olApt.Subject
.Cells(NextRow, "B").Value = CDate(olApt.Start)
.Cells(NextRow, "C").Value = olApt.Location
.Cells(NextRow, "D").Value = olApt.Categories
Dim recip As Object
Dim allRecip As String
For Each recip In olApt
Debug.Print (recip.Address)
.Cells(NextRow, "E").Value = olApt.Address
Next
NextRow = NextRow + 1
Else
End If
Next olApt
.Columns.AutoFit
End With
Set olApt = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Sub
UPDATE
I tried
For Each recip in olApt.recipients
.Cells(NextRow, "E").Value = olApt.recipients.Address
Next
And I still get the errors below.
This is the error
Here are two parts of the Watch on olApt
UPDATE 2
The answer works on my laptop but crashes on my desktop (seperate outlook account). This is the line it crashes on, and I not it wont let the "R" in recipients be a captial (it changes to lower case automatically despite typing a captial).
I also note that the Recipients collection on olApt is different on my laptop to my desktop:

The line
Cells(NextRow, "E").Value = olApt.recipients.Address
must be replaced with
.Cells(NextRow, "E").Value = recip.Address
Also keep in mind that Outlook Security can blocks access to properties such as SenderEmailAddress or Recipients if an antivirus app is not installed or is out of date. See https://learn.microsoft.com/en-us/office/vba/outlook/how-to/security/security-behavior-of-the-outlook-object-model

Related

How to copy text from a textbox in excel to paste it into an email. VBA

I'm trying to improve the macro for sending files to clients.
Everything was fine until the boss decided that the email text should be left in the correct format. Previously, the macro took the text from a cell. I am now trying to change this so that the email text retains the format. Highlights, hyperlinks etc.
I have changed the original macro several times according to what I found on the internet but I keep getting an error. Unfortunately I am just starting with VBA and I am already lost here.
I would be very grateful for your help.
Keep the format of a text box in excel and insert it in an email body
enter image description here
enter image description here
Sub Mail()
Dim wb As Workbook
Dim OutApp As Object
Dim OutMail As Object
Dim olInsp As Object
Dim xlSheet As Worksheet
Dim wdDoc As Object
Dim oRng As Object
Set wb = Workbooks("BankDetails.xlsm")
Set ws = wb.Sheets("MessageBody")
Set ws1 = wb.Sheets("Data")
Set ws2 = wb.Sheets("Batch")
Set xlSheet = ActiveWorkbook.Sheets("MessageBody")
xlSheet.TextBoxes("TextBox 1").Copy
Dim i As Long
Dim i2 As Long 'For the number of passes (?)
lastRow = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow
klient = ws2.Cells(i, "A")
zalacznik1 = ws.Cells(4, "B") & ws.Cells(5, "B")
zalacznik2 = ws.Cells(4, "B") & ws.Cells(6, "B")
zalacznik3 = ws.Cells(4, "B") & ws.Cells(7, "B")
Set OutApp = CreateObject("Outlook.Application")
'Create Item Outlook Element
Set OutMail = OutApp.CreateItem(0)
With OutMail
'Sender e-mail address
.SentOnBehalfOfName = ws.Cells(1, "B")
'E-mail address of the recipient, can also be several with ; separate
'.To = ws2.Cells(i, "B")
.BodyFormat = 3
.BCC = ws2.Cells(i, "B")
'from column C
.Subject = ws2.Cells(i, "C")
'The text to send in column D
'Maximum 1024 characters
'The text is accepted without formatting
'.body = body
'Add attachements w. reference to column B in sheets1 / MessageBody
.Attachments.Add (zalacznik1)
.Attachments.Add (zalacznik2)
.Attachments.Add (zalacznik3)
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
Set oRng = wdDoc.TextBoxes
oRng.collapse 1
oRng.Paste
'Here the mail is displayed
.Display
'Here the e-mail is immediately placed in the outbox
'.Send
End With
'Empty object variables
Set OutApp = Nothing 'CreateObject("Outlook.Application")
Set OutMail = Nothing 'OutApp.CreateItem(0)
Set olInsp = Nothing
Set wdDoc = Nothing
Set oRng = Nothing
'Turn on pause
'Outlook can't process the orders quickly enough, hence the pause
Application.Wait (Now + TimeValue("0:00:02"))
' ws2.Cells(i, "D") = "Done"
ws2.Cells(i, "D").Value = "Done, " & Now()
Next i
End Sub
By using the WordEditor you have access to a big part of MS Words Object model, including it's Range object, so you can use its PasteSpecial method.
In the below code I also made a few other minor changes such as taking the Outlook.Application object out of the loop (why would you open and close Outlook every time?) and using the existing Outlook.Application object if it's already open.
Sub Mail()
Dim wb As Workbook
Dim OutApp As Object
Dim OutMail As Object
Dim xlSheet As Worksheet
Dim wdDoc As Object
Dim oRng As Object
Set wb = Workbooks("BankDetails.xlsm")
Set ws = wb.Sheets("MessageBody")
Set ws1 = wb.Sheets("Data")
Set ws2 = wb.Sheets("Batch")
Set xlSheet = ActiveWorkbook.Sheets("MessageBody")
xlSheet.TextBoxes("TextBox 1").Copy
Dim i As Long
Dim i2 As Long 'For the number of passes (?)
lastRow = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
On Error GoTo 0
If outApp Is Nothing Then
Set outApp = CreateObject("Outlook.Application")
End If
For i = 2 To lastRow
klient = ws2.Cells(i, "A")
zalacznik1 = ws.Cells(4, "B") & ws.Cells(5, "B")
zalacznik2 = ws.Cells(4, "B") & ws.Cells(6, "B")
zalacznik3 = ws.Cells(4, "B") & ws.Cells(7, "B")
'Create Item Outlook Element
Set OutMail = OutApp.CreateItem(0)
With OutMail
'Sender e-mail address
.SentOnBehalfOfName = ws.Cells(1, "B")
'E-mail address of the recipient, can also be several with ; separate
'.To = ws2.Cells(i, "B")
.BodyFormat = 3
.BCC = ws2.Cells(i, "B")
'from column C
.Subject = ws2.Cells(i, "C")
.Display 'Needs to be displayed before opening Word Inspector
Set wdDoc = .GetInspector.WordEditor
'The text to send in column D
'Maximum 1024 characters
ws2.Cells(i, "D").Copy
wdDoc.Paragraphs.first.Range.PasteSpecial 16 'wdFormatOriginalFormatting
'.body = body
'Add attachements w. reference to column B in sheets1 / MessageBody
.Attachments.Add zalacznik1
.Attachments.Add zalacznik2
.Attachments.Add zalacznik3
' Set oRng = wdDoc.TextBoxes
' oRng.collapse 1
' oRng.Paste
'Here the e-mail is immediately placed in the outbox
'.Send
End With
'Empty object variables
Set OutMail = Nothing 'OutApp.CreateItem(0)
Set olInsp = Nothing
Set wdDoc = Nothing
Set oRng = Nothing
'Turn on pause
'Outlook can't process the orders quickly enough, hence the pause
Application.Wait (Now + TimeValue("0:00:02"))
' ws2.Cells(i, "D") = "Done"
ws2.Cells(i, "D").Value = "Done, " & Now()
Next i
End Sub

Accessing Custom Outlook Calendar Entries

I'm trying to access calendar entries from 2 custom Outlook calendars using Excel VBA.
I've obtained some code which gives me what I want from the default calendar but I cannot see how to change the location to my own calendars.
The code I'm using is
Sub ListAppointments()
Dim olApp As Object
Dim olNS As Object
Dim olFolder As Object
Dim olApt As Object
Dim nextrow As Long
Dim FromDate As Date
Dim ToDate As Date
FromDate = CDate("30/11/2021")
ToDate = CDate("20/12/2021")
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9)
nextrow = 2
With Sheets("Cal-Ext")
.Range("A1:E1").Value = Array("Date", "Start Time", "End Time", "Subject", "Location")
For Each olApt In olFolder.Items
If (olApt.Start >= FromDate And olApt.Start <= ToDate) Then
.Cells(nextrow, "A").Value = CDate(olApt.Start)
.Cells(nextrow, "A").NumberFormat = "DD/MM/YYYY"
.Cells(nextrow, "B").Value = olApt.Start
.Cells(nextrow, "B").NumberFormat = "HH:MM"
.Cells(nextrow, "C").Value = olApt.End
.Cells(nextrow, "C").NumberFormat = "HH:MM"
.Cells(nextrow, "D").Value = olApt.Subject
.Cells(nextrow, "E").Value = olApt.Location
nextrow = nextrow + 1
Else
End If
Next olApt
Set olFolder = olNS.GetDefaultFolder(9)
nextrow = nextrow + 5
For Each olApt In olFolder.Items
If (olApt.Start >= FromDate And olApt.Start <= ToDate) Then
.Cells(nextrow, "A").Value = CDate(olApt.Start)
.Cells(nextrow, "A").NumberFormat = "DD/MM/YYYY"
.Cells(nextrow, "B").Value = olApt.Start
.Cells(nextrow, "B").NumberFormat = "HH:MM"
.Cells(nextrow, "C").Value = olApt.End
.Cells(nextrow, "C").NumberFormat = "HH:MM"
.Cells(nextrow, "D").Value = olApt.Subject
.Cells(nextrow, "E").Value = olApt.Location
nextrow = nextrow + 1
Else
End If
Next olApt
.Columns.AutoFit
End With
Set olApt = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Sub
I need to change the set olfolder command before the second loop to select my own calendar but nothing I've tried works.
Outlook calendar
Current excel result
Here is a quick code that I wrote to loop through all the navigation folders of My Calendars
This code was tested in MS Outlook. You may have to edit it for it to work in MS Excel.
Option Explicit
Sub Sample()
Dim oNameSpace As Object
Dim oExplorer As Object
Dim oMainFolder As Object
Dim oCalModule As Object
Dim oSubFolder As Object
Dim oCalNavFolders As Object
Dim i As Long
Dim objitem As Object
Set oNameSpace = Outlook.GetNamespace("MAPI")
Set oExplorer = oNameSpace.GetDefaultFolder(9).GetExplorer
Set oCalModule = oExplorer.NavigationPane.Modules.GetNavigationModule(1)
Set oCalNavFolders = oCalModule.NavigationGroups.Item("My Calendars").NavigationFolders
For i = 1 To oCalNavFolders.Count
Set objitem = oCalNavFolders(i)
On Error Resume Next
Set oSubFolder = objitem.Folder
On Error GoTo 0
If Not oSubFolder Is Nothing Then
Debug.Print oSubFolder.Name
If oSubFolder.Name = "Area1" Then
With oSubFolder
'
'~~> Do what you want
'
End With
Exit For
End If
Set oSubFolder = Nothing
End If
Next i
End Sub
Screenshot
Code from Excel
Option Explicit
Sub ListAppointments()
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
Dim oNameSpace As Object
Dim oExplorer As Object
Dim oMainFolder As Object
Dim oCalModule As Object
Dim oSubFolder As Object
Dim oCalNavFolders As Object
Dim i As Long
Dim objitem As Object
Set oNameSpace = OutApp.GetNamespace("MAPI")
Set oExplorer = oNameSpace.GetDefaultFolder(9).GetExplorer
Set oCalModule = oExplorer.NavigationPane.Modules.GetNavigationModule(1)
Set oCalNavFolders = oCalModule.NavigationGroups.Item("My Calendars").NavigationFolders
For i = 1 To oCalNavFolders.Count
Set objitem = oCalNavFolders(i)
On Error Resume Next
Set oSubFolder = objitem.Folder
On Error GoTo 0
If Not oSubFolder Is Nothing Then
Debug.Print oSubFolder.Name
If oSubFolder.Name = "Area1" Then
With oSubFolder
'
'~~> Do what you want
'
End With
Exit For
End If
Set oSubFolder = Nothing
End If
Next i
End Sub

Getting reccuring appointments VBA

Can somebody please help me out. I have this code and it reads all appointments from the calendar for specific dates; however, the code doesn't display any recurring meetings within given dates:
ToDate = CDate("10/12/2019")
FromDate = CDate("10/06/2019")
'On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9) 'olFolderCalendar
'include reccuring items
'-------------------------
olFolder.Items.Sort ("[Start]")
olFolder.Items.IncludeRecurrences = True
'-------------------------
NextRow = 2
With Sheets("Sheet1") 'Change the name of the sheet here
.Range("A1:F1").Value = Array("Report Date", "Date", "Time spent", "Location", "Categories", "Title")
For Each olApt In olFolder.Items
If (olApt.Start >= FromDate And olApt.Start <= ToDate) Then
.Cells(NextRow, "A").Value = Format(Now, "DD-MM-YY")
.Cells(NextRow, "B").Value = CDate(olApt.Start)
.Cells(NextRow, "C").Value = olApt.End - olApt.Start
.Cells(NextRow, "C").NumberFormat = "HH:MM"
.Cells(NextRow, "E").Value = olApt.Categories
.Cells(NextRow, "F").Value = olApt.Subject
NextRow = NextRow + 1
Else
End If
Next olApt
.Columns.AutoFit
End With
Can somebody please help me out and let me know what I am doing wrong?!
Thank you!
Items in a folder have to be made into a collection to then manipulate.
On Error Resume Next ' This is a rare proper use.
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9) 'olFolderCalendar
Set itmCollection = olFolder.Items
'include recurring items
'-------------------------
itmCollection.Sort ("[Start]")
itmCollection.IncludeRecurrences = True
'-------------------------
For Each olApt In itmCollection
Demo code
Option Explicit
Sub apptsInDateRangeIncludingRecurrences()
Dim ToDate As Date
Dim FromDate As Date
Dim olApp As Object
Dim olNS As Object
Dim olFolder As Object
Dim itmCollection As Object
Dim itmCollectionFrom As Object
Dim itmCollectionFromTo As Object
Dim sFilter As String
Dim olApt As Object
ToDate = CDate("10/12/2019")
FromDate = CDate("10/06/2019")
On Error Resume Next ' This is a rare proper use.
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9) 'olFolderCalendar
Set itmCollection = olFolder.Items
'include recurring items
'-------------------------
itmCollection.Sort ("[Start]")
itmCollection.IncludeRecurrences = True
'-------------------------
'Filter for applicable items
sFilter = "[Start]>='" & FromDate & "'"
'Debug.Print sFilter
Set itmCollectionFrom = itmCollection.Restrict(sFilter)
sFilter = "[Start]<='" & ToDate & "'"
'Debug.Print sFilter
Set itmCollectionFromTo = itmCollectionFrom.Restrict(sFilter)
For Each olApt In itmCollectionFromTo
If olApt.Start >= FromDate Then
Debug.Print olApt.Start & " " & olApt.Subject
End If
Next olApt
Debug.Print "Done."
End Sub

Use Excel to make appointment in All Public Folders Calendar in 2013 MS Exchange

My code works fine in the default calendar but I am unable to get it to made an appointment in the AllPublicFolders Calendar. I am unable to call the function GetPublicFolder because I am new using VBA. Any help would be greatly appreciated.
Here is my code with "Big Store A Calendar in the all public folders:
Option Explicit
Sub RegisterAppointmentList()
' adds a list of appointments to the Calendar in Outlook
Dim olApp As Outlook.Application
Dim olAppItem As Outlook.AppointmentItem
Dim r As Long
On Error Resume Next
'Worksheets("Schedule").Activate
Worksheets("Appt").Activate
Set olApp = GetObject("", "Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then
On Error Resume Next
Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then
MsgBox "Outlook is not available!"
Exit Sub
End If
End If
'r = 6 ' first row with appointment data in the active worksheet
r = 2 ' first row with appointment data in the active worksheet
Dim mysub, myStart, myEnd
While Len(Cells(r, 2).Text) <> 0
mysub = Cells(r, 2) & ", " & Cells(r, 3)
myStart = DateValue(Cells(r, 5).Value) + Cells(r, 6).Value
myEnd = DateValue(Cells(r, 7).Value) + Cells(r, 8).Value
'DeleteTestAppointments mysub, myStart, myEnd
Set olAppItem = olApp.CreateItem(olAppointmentItem) ' creates a new appointment
With olAppItem
' set default appointment values
.Location = Cells(r, 2)
.Body = Cells(r, 3).Value
.ReminderSet = False
.BusyStatus = olFree
'.RequiredAttendees = "johndoe#microsoft.com"
On Error Resume Next
.Start = myStart
.End = myEnd
.Subject = Cells(r, 1)
.Location = Cells(r, 2)
.Body = Cells(r, 3).Value
'.ReminderSet = True
'.BusyStatus = olBusy
.Categories = Cells(r, 4).Value
On Error GoTo 0
.Save ' saves the new appointment to the default folder
End With
r = r + 1
Wend
Set olAppItem = Nothing
Set olApp = Nothing
' Print the Appt Sheet
Sheets("Sheet1").PrintOut
MsgBox "The Appt Sheet Printed and the Appt was entered in your default calendar on May 31st!"
End Sub
‘-------------------------I Need to get correct Public folder for the Exchange calendar -------------
‘I am using VBA for excel workbooks and need to create appointments in 2 public folder shared calendars
‘I need to get code like the code below to create appointments in the shared public calendar – ‘
‘I determine which calendar for the appointment using a workbook cell which is a list box of the 2 calendar names –
‘ Big Store A Calendar or Big Store B Calendar
' GetFolder - Gets a Public folder based on a string path - e.g.
'If Folder name in English is
'Public Folders\All Public Folders\Big Store A Calendar or
‘'Public Folders\All Public Folders\Big Store B Calendar
Public Function GetPublicFolder(strFolderPath)
Dim colFolders
Dim objFolder
Dim arrFolders
Dim i
On Error Resume Next
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders = Split(strFolderPath, "\")
Set objFolder = Application.Session.GetDefaultFolder(18) ‘This is the correct folder # for “All Public Folders”
Set objFolder = objFolder.Folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For i = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(i))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
Set GetPublicFolder = objFolder
Set colFolders = Nothing
' Set objApp = Nothing
Set objFolder = Nothing
End Function
Application in Set objFolder = Application.Session.GetDefaultFolder(18) is Excel. You want to use Outlook.
Sub DisplyOutlookPublicFolderFromExcel()
Dim olApp As Outlook.Application
Dim olAppItem As Outlook.AppointmentItem
Dim pubCal As Folder
Set olApp = CreateObject("Outlook.Application")
Set pubCal = GetPublicFolder(olApp, "All Public Folders\Big Store A Calendar")
pubCal.Display
Set olAppItem = Nothing
Set olApp = Nothing
Set pubCal= Nothing
End Sub
Public Function GetPublicFolder(objApp, strFolderPath)
Dim colFolders
Dim objFolder
Dim arrFolders
Dim i
On Error Resume Next
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders = Split(strFolderPath, "\")
Set objFolder = objApp.Session.GetDefaultFolder(18) 'This is the correct folder # for “All Public Folders”
Set objFolder = objFolder.Folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For i = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(i))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
Set GetPublicFolder = objFolder
Set colFolders = Nothing
Set objApp = Nothing
Set objFolder = Nothing
End Function

Macro fails to create appointments based on worksheet data

I have an Excel macro that I run, which takes activity names, dates and times from the spreadsheet and places them into the Outlook calendar. This works fine when Outlook is running, but when it is not, the macro does not make the appointments.
I have made an error checking piece that checks to see if a running instance of Outlook is running and if not creates one but it still only works when Outlook is running.
Any ideas why??
Sub SetAppt()
' Dim olApp As Outlook.Application
Dim olApt As AppointmentItem
Dim olApp As Object
'if an instance of outlook is not open then create an instance of the application
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If er.Number = 429 Then
Set olApp = CreateObject("Outlook.Application.14")
End If
On Error GoTo 0
Set olApp = CreateObject("Outlook.Application")
' Set olApp = New Outlook.Application
'declare an index for all the variables
Dim i As Integer
i = 2
'declare the variables that will hold the data and set their initial value
Dim occ, actName, srtTime, duration As String
occ = "A" & i
actName = "B" & i
srtTime = "F" & i
duration = "G" & i
'for holding different parts of the dates/times that will be split
Dim splitStr() As String
Dim splitDrtion() As String
'loop until there is no more items
While Range(occ).Value <> ""
'create a new appointment
Set olApt = olApp.CreateItem(olAppointmentItem)
'we must split the start time and date
splitStr = Split(Range(srtTime).Value, " ")
Dim oDate As Date
oDate = splitStr(0)
'we must also spilt the duration (number/hour)
splitDrtion = Split(Range(duration).Value, " ")
'with is used to acces the appointment items properties
With olApt
.Start = oDate + TimeValue(splitStr(1))
'if the duration is in hours then multiply number else leave it
If splitDrtion(1) = "Hour" Then
.duration = 60 * splitDrtion(0)
Else
.duration = splitDrtion(0)
End If
.Subject = Range(occ).Value
.Body = Range(actName).Value
.Save
End With
'increment i and reset all the variables with the new number
i = i + 1
occ = "A" & i
actName = "B" & i
srtTime = "F" & i
duration = "G" & i
Set olApt = Nothing
Wend
Set olApp = Nothing
End Sub
Building on Siddharth's example, here is a refactored version of your code.
Sub SetAppt()
Dim olApt As Object ' Outlook.AppointmentItem
Dim olApp As Object ' Outlook.Application
Dim i As Long
Dim apptRange As Variant
Const olAppointmentItem As Long = 1
' create outlook
Set olApp = GetOutlookApp
If olApp Is Nothing Then
MsgBox "Could not start Outlook"
Exit Sub
End If
' read appts into array
apptRange = Range(Cells(2, 1), Cells(Rows.Count, 7).End(xlUp)).value
For i = LBound(apptRange) To UBound(apptRange)
Set olApt = olApp.CreateItem(olAppointmentItem)
With olApt
.Start = apptRange(i, 6)
If InStr(apptRange(i, 7), "Hour") > 0 Then
' numeric portion cell is delimited by space
.Duration = 60 * Split(apptRange(i, 7), " ")(0)
Else
.Duration = apptRange(i, 7)
End If
.Subject = apptRange(i, 1)
.Body = apptRange(i, 2)
.Save
End With
Next i
End Sub
Function GetOutlookApp() As Object
On Error Resume Next
Set GetOutlookApp = CreateObject("Outlook.Application")
End Function
This code reads your worksheet data into an array. This avoids the time penalty that comes from the COM interaction between VBA and Excel.
We loop through the array and create a new appointment for each row.
Using the following sample data, it worked regardless of whether Outlook was open or not (Outlook being closed makes it obviously slower, however).
There is in fact no need to check if Outlook is open.
Instead of
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If er.Number = 429 Then
Set olApp = CreateObject("Outlook.Application.14")
End If
On Error GoTo 0
Set olApp = CreateObject("Outlook.Application")
Try this
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set olApp = CreateObject("Outlook.Application")
End If
Err.Clear
On Error GoTo 0
Since I cannot test it, here is your code with the necessary updates. Please try this.
Sub SetAppt()
Dim olApt As Object, olApp As Object
Dim i As Integer
Dim occ As String, actName As String, srtTime As String, duration As String
Dim splitStr() As String, splitDrtion() As String
Dim oDate As Date
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set olApp = CreateObject("Outlook.Application")
End If
Err.Clear
On Error GoTo 0
'declare an index for all the variables
i = 2
'declare the variables that will hold the data and set their initial value
occ = "A" & i
actName = "B" & i
srtTime = "F" & i
duration = "G" & i
'loop until there is no more items
While Range(occ).Value <> ""
'create a new appointment
Set olApt = olApp.CreateItem(1)
'we must split the start time and date
splitStr = Split(Range(srtTime).Value, " ")
oDate = splitStr(0)
'we must also spilt the duration (number/hour)
splitDrtion = Split(Range(duration).Value, " ")
'with is used to acces the appointment items properties
With olApt
.Start = oDate + TimeValue(splitStr(1))
'if the duration is in hours then multiply number else leave it
If splitDrtion(1) = "Hour" Then
.duration = 60 * splitDrtion(0)
Else
.duration = splitDrtion(0)
End If
.Subject = Range(occ).Value
.Body = Range(actName).Value
.Save
End With
'increment i and reset all the variables with the new number
i = i + 1
occ = "A" & i
actName = "B" & i
srtTime = "F" & i
duration = "G" & i
Set olApt = Nothing
Wend
Set olApp = Nothing
End Sub

Resources